Skip to content

Instantly share code, notes, and snippets.

@ChrisMoney
Created September 7, 2024 17:42
Show Gist options
  • Save ChrisMoney/d6743cdc7b750fd21de4f989a129a736 to your computer and use it in GitHub Desktop.
Save ChrisMoney/d6743cdc7b750fd21de4f989a129a736 to your computer and use it in GitHub Desktop.
Replicating C Pointer in C#
// 1) 'ref'
// ref keyword means "pass by reference" - edits
// made in this function affect the actual variable
int someNum = 5;
AddOne(ref someNum);
// someNum now = 6
void AddOne(ref int i)
{
i++;
}
// 2) 'return'
// As stated you could return the value instead
int someNum = 5;
// Call AddOne, passing in our someNum value and set the value
// that AddOne returns back into out someNum variable.
someNum = AddOne(someNum);
int AddOne(int i)
{
// You could return right away by doing something like
// return ++i;
// however for verbosity, im not in this example.
i += 1;
return i;
}
// 3) 'Extension method'
int someNum = 5;
// I cant think of how to correctly say what an extension method
// actually is so heres a link:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
// https://www.dotnetperls.com/extension
someNum.AddOne();
public static int AddOne(this int i)
{
i += 1;
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment