I’m currently looking into C# Generics, and I have a few questions.
1) In the following code, will the comparison of the type of T in “Test” slow down the program? In other languages this is handled on compile time, but I don’t know about C#.
2) Since sizeof apparently won’t work, I have to use System.Runtime.InteropServices.Marshal.SizeOf. Is this correct?
3) I haven’t seen code like this in C# yet, is there anything wrong about it, or is it perfectly fine what I’m doing here? In the end the method in this example would take a handful of types, and throw and exception if it can’t handle it. Some types would be handled independently, others like short/int/long would be handled together, depending on their size.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Test<int>();
Test<long>();
Test<string>();
Console.ReadLine();
}
static void Test<T>()
{
Type type = typeof(T);
if (type == typeof(int) || type == typeof(long))
{
Console.WriteLine("int");
Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(type).ToString());
}
else if (type == typeof(string))
{
Console.WriteLine("string");
}
}
}
}
Yes, the type comparison slows it down, not that such an operation will significantly affect anything done only once. If you’re doing this in a tight loop somewhere… consider not doing it. This is because it creates a
Typeobject and compares thoseTypeobjects – it’s not a compile-time check.Yes,
Marshal.SizeOfis correct1. I don’t know what C#’ssizeofdoes, though, because I’m a VB.NET person.As for not seeing this type of code much in C#, that’s probably because it’s not a case that people often come across. And also, instead of doing what you’re doing, you should be offering method overloads for each type; cleaner, and the error is at compile-time, not runtime.
1 You’re just printing it out, it’s correct to print it out. I don’t know what the goal of all this is, though.