Tutorial by Examples

Given the following definitions : public interface IMyInterface1 { string GetName(); } public interface IMyInterface2 { string GetName(); } public class MyClass : IMyInterface1, IMyInterface2 { string IMyInterface1.GetName() { return "IMyInterface1"...
If you know that a value is of a specific type, you can explicitly cast it to that type in order to use it in a context where that type is needed. object value = -1; int number = (int) value; Console.WriteLine(Math.Abs(number)); If we tried passing value directly to Math.Abs(), we would get a ...
If you aren't sure whether a value is of the type you think it is, you can safely cast it using the as operator. If the value is not of that type, the resulting value will be null. object value = "-1"; int? number = value as int?; if(number != null) { Console.WriteLine(Math.Abs(nu...
A value will automatically be cast to the appropriate type if the compiler knows that it can always be converted to that type. int number = -1; object value = number; Console.WriteLine(value); In this example, we didn't need to use the typical explicit casting syntax because the compiler knows...
If you need to know whether a value's type extends or implements a given type, but you don't want to actually cast it as that type, you can use the is operator. if(value is int) { Console.WriteLine(value + "is an int"); }
Explicit casting operators can be used to perform conversions of numeric types, even though they don't extend or implement one another. double value = -1.1; int number = (int) value; Note that in cases where the destination type has less precision than the original type, precision will be lost....
In C#, types can define custom Conversion Operators, which allow values to be converted to and from other types using either explicit or implicit casts. For example, consider a class that is meant to represent a JavaScript expression: public class JsExpression { private readonly string expres...
Suppose you have types like the following: interface IThing { } class Thing : IThing { } LINQ allows you to create a projection that changes the compile-time generic type of an IEnumerable<> via the Enumerable.Cast<>() and Enumerable.OfType<>() extension methods. IEnumerabl...

Page 1 of 1