Geek Culture
Published in

Geek Culture

Hidden C# Gem Codes

Hi, today we will talk about interesting and useful C# codes which are not known so much.

1. First Example is about using “out parameter” in Class Constructor:

So when we send any out parameter to Class Constructor, we don’t need to return anything. Only changing the reference of “array3List” is enough.

  • We will get the int[ ] parameter with “arrayList” and divide it by 3 and finally we will put all array parts to out parameter 2 dimensions int[,] “array3List”.
  • We will slice the array and we will set every length of the part as 3. We will set the length of int[,] 2 dimension array the first column is the count of arrays and the second one is of course length of the array so 3. We will use a counter for iteration to every item of arrayList.
  • We will loop until count of arrayList. We will get 3 item from arrayList for every array of out parameter array3List.
  • “if counter ≥arrayList.Length” => We will write this condition because some arrays count could be less than 3.
  • “dividedList[i,num] = arrayList[counter]”: We will set every item in arrayList to int[,] 2 dimension array.
  • “array3List = dividedList” : Finally we will set array3List for the result.

Program.cs/ArrayDivedOperation :

public class ArrayDivedOperation
{
public ArrayDivedOperation(int[] arrayList, out int[,] array3List)
{
int count = (int)Math.Ceiling((double)arrayList.Length / 3);
int[,] dividedList = new int[count, 3];
int counter = 0;
for (int i = 0; i < count; i++)
{
for (int num = 0; num < 3; num++)
{
if (counter >= arrayList.Length) { break; }
dividedList[i, num] = arrayList[counter];
counter++;
}
}
array3List = dividedList;
}
  • int[] array is our test array.
  • int[,] list3Group is our out parameter result array.
  • ArrayDivedOperation arrayDiveded = new(array, out list3Group): We will create ArrayDivedOperation class and send out parameter on Constructor.
  • list3Group.GetLength(0): We will loop in every array of list3Group.
  • for (int i2 = 0; i2 < 3; i2++): We will get every column per array in list3Group
  • Console.Write(list3Group[i, i2] + “,”): We will write every item by 3 groups on console.

Program.cs/Main() :

static void Main(string[] args)
{
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
int[,] list3Group = new int[array.Length, 3];
ArrayDivedOperation arrayDiveded = new(array, out list3Group);
for (int i = 0; i < list3Group.GetLength(0); i++)
{
for (int i2 = 0; i2 < 3; i2++)
{
Console.Write(list3Group[i, i2] + ",");
}
Console.WriteLine();
}
}

Result: Finally, we changed the reference of out parameter “array3List” on Class Constructor. So we didn’t need to return any parameters.

2. C# can recognize positive, negative, and zero numbers when you use “;” in string format.

Program.cs:

int[] arr = { -1, -3, 0, 0, 2, 5};
foreach (var item in arr)
{
Console.WriteLine($"{item} is {item:positive number;negative number;zero}");
}

Result:

3. On C#11 Preview You can use “List Patterns” in “Patterning Matching”. And you can “Sum()” middle numbers in an array. I think Microsoft will take “ListPattern” much further in the future.

Program.cs:

int[] arr = { 4, 6, 2, 8, 10 };
int result = arr switch
{
[] => 0,
[_, int second] => second,
[_, .. int[] middle, _] => middle.Sum(),
_=>-1
};
Console.WriteLine(result); //16

Result:

4. On C#11 Preview You can create Generic Attribute. How about set complex type parameters to the Custom Attribute class :)

  • “BaseModel” is our root model. All Bussines models are inherited from “BaseModel”. User Model and Product Model are our business models.
  • IResponseModel<T> is our Generic Attribute class, interface. T is inherited from BaseModel. So User or Product models can be replaced with “T”.
  • Generic ResponseAttribute<T> is inherited from IResponseModel so T must come from “BaseModel” too.
  • ResponseAttribute takes 3 parameter on Constructor. string Message, Success and T Data property. “data”parameter will be set by using Deserialize<T>() method. String parameter converted to class. For this example, it is User or Product class.
  • And finally WriteModel() method must be implemented because of IResponseModel<T> inheritance. It is used for printing “T” ModelName,Email and Id to the console.
  • You can only set primitive types like string, int, or date as a parameter to the Attribute class. So to set User or Product classes as a parameter to the <T> Data, We have to convert them to the JSON string as seen below. Next, we set string message parameter and bool success parameters for User and Product ResponseAttribute.
Json String Example T Data “User”
  • SaveUserLog() method is represent <User> and SaveProduct() method is represent <Product> table ResponseModel. We will get these method references, by using the “GetRuntimeMethod()” reflection method. And we will get their’s attribute, by using the “GetCustomAttribute()” reflection method.
  • At the end we will get ResponseAttribute<User> and ResponseAttribute<Product> class, and call their’s WriteModel() method, which is inherited from “IResponseModel<T>”.
  • This is our Static Main() method. We will call these “SaveUserLog()” and “SaveProductLog()” method for testing here.
Static Main() Method

This is Result Screen: We will get the User and Product model from Method Attribute(ResponseAttribute<T>) and Print this <T> Data Parameter to the Console by using Deserialize() method.

Final Result Screen

With this example, we use Generic CustomAttribute to take a class as a parameter. Normally in C#, CustomAttribute class can not take complex type as a parameter. But with GenericAttribute<T>, it is possible to take by using Deserialize<T>() method and convert string json to the spesific class.

Program.cs:

Conclusion:

Even though I’ve been writing C# for 20 years, it still surprises me. The reason for this is that it is designed to be used in many different areas apart from continuous innovations and improvements.

See you until the next article.

Thank You For Reading..

“If you have read so far, first of all, thank you for your patience and support. I welcome all of you to my blog for more!”

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bora Kaşmer

Bora Kaşmer

2.1K Followers

I have been coding since 1993. I am computer and civil engineer. Microsoft MVP. Senior Software Architect. Ride motorcycle. Gamer. Have two daughters.