how to use generics in c# code example
Example 1: how to use variables in c#
int MyNumber = 2;
float MyDotNumber = 2.2;
string MyText = ("Hello World")
bool YesOrNo = true;
(Type) (Name) = (Value);
E.g:
int NameOfVariable = (Value depending on type)
Example 2: generics in c#
class MyGenericClass<T>
{
private T genericMemberVariable;
public MyGenericClass(T value)
{
genericMemberVariable = value;
}
public T genericMethod(T genericParameter)
{
Console.WriteLine("Parameter type: {0}, value: {1}", typeof(T).ToString(),genericParameter);
Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(), genericMemberVariable);
return genericMemberVariable;
}
public T genericProperty { get; set; }
}
Example 3: how to use lambda in java
StateOwner stateOwner = new StateOwner();
stateOwner.addStateListener(
(oldState, newState) -> System.out.println("State changed")
);
Example 4: generic method c#
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
public static void TestSwap()
{
int a = 1;
int b = 2;
Swap<int>(ref a, ref b);
System.Console.WriteLine(a + " " + b);
}