TypeCode is a built-in enumeration type in C# that represents the type of an object. It contains a list of values that represent the type of data in an object, such as integer, string, or DateTime. This can be useful when performing type checking on objects or creating generic methods and classes that work on different types of data.
Example 1: Type checking using TypeCode
int x = 10; if (Type.GetTypeCode(x) == TypeCode.Int32) { Console.WriteLine("x is an integer"); }
In this example, the GetTypeCode method is used to retrieve the TypeCode value for the integer variable x. The code then checks if the TypeCode matches the Int32 value, indicating that x is an integer.
Example 2: Creating a generic method using TypeCode
public static void PrintValue(T value) { TypeCode code = Type.GetTypeCode(typeof(T)); switch(code) { case TypeCode.Int32: Console.WriteLine($"The value is an integer: {value}"); break; case TypeCode.String: Console.WriteLine($"The value is a string: {value}"); break; default: Console.WriteLine("Unknown type!"); break; } }
This method takes a generic parameter value of type T and uses GetTypeCode to determine its TypeCode value. Depending on the TypeCode, it prints a message identifying the type of value passed in. This method can be used for any type of value, as long as it has a TypeCode value.
Package/library: This functionality is part of the System namespace in the .NET Framework, which is included in the Microsoft .NET Framework class library. No additional library or package is required.
C# (CSharp) TypeCode - 60 examples found. These are the top rated real world C# (CSharp) examples of TypeCode extracted from open source projects. You can rate examples to help us improve the quality of examples.