using in and as with a struct

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How can you get a custom struct to work with the "in" and "as" keywords, for
example, (myObject is myStruct).....see full code example below....


private void CreateArray(ArrayList myArray)
{
ArrayList newArray= new ArrayList();

foreach (object item in myArray)
{
if (item is myStruct) //this doesn't work, myStruct is a
ValueType
{
newArray.Add(new exampleType1
(item as myStruct)); //this doesn't work, myStruct
is a ValueType
}
else if (item is anotherStruct)
{
newArray.Add(new exampleType2
(item as anotherStruct));
}
}
}
 
How can you get a custom struct to work with the "in" and "as" keywords, for
example, (myObject is myStruct).....see full code example below....

is should just work with structs.

as can't be used with structs since as would return null if the cast
fails, and value types aren't nullable.



Mattias
 
The is operator should work fine with value types. Are you getting
compiled time errors? As for 'as', it works only if the destination
type is a reference type. You can simply do
if (item is mystruct)
val = (mystruct) item;

Regards
Senthil
 
Back
Top