How to Perform User Defined Conversions Between Structures (Struct)?When dealing
with data types in C#, you might have to perform type conversions. You
do it using explicit casting or implicit casting. For example converting
from integer to double is an example of implicit casting and the vice
versa conversion from double to integer requires explicit casting.
To your surprise, C# allows you to perform such implicit and explicit type conversions in user defined types like classes and structures as well. You can do such conversions using conversion keywords provided by C#: implicit, explicit, operator. Given below is an example to show user defined conversion between structures: struct sampleStruct1
{ Output of this example will be: struct2Obj contains 525 In this example, you have two structures namely sampleStruct1 and sampleStruct2. In both the structures, you perform user defined conversions to do the following: To implicitly cast an integer to the structure using the method sampleStruct1(int data), sampleStruct2(int data). By doing so, you can directly assign integer values to these structure instances. Hence the statement struct1Obj = 525 in Main method of testClass is legal. Because of this statement, the value 525 is set as member1 in the structure sample1Struct. To implicitly cast sampleStruct2 instance to sampleStruct1 instance using the method sampleStruct1(sampleStruct2 struct2Obj). By defining this method, you can directly assign sample2Struct object to sample1Struct object as: struct1Obj = struct2Obj To explicitly cast structure to integer using the methods int(sampleStruct1 struct1Obj) and int(sampleStruct2 struct2Obj). Hence when you assign struct1Obj to integer or struct2Obj to integer, you have to cast them using (int) as shown in the Main method of testClass
|