mfenske17363
asked on
Is it possible to cast to generic 'object' type?
Sorry for the C# beginner question but here goes...
say I have a declared type such as:
[StructLayout(LayoutKind.S equential, Pack = 1)]
public struct SAMPLE_STRUCT
{
public UInt32 size;
public Boolean boolVar;
public Int32 intVar;
};
and have instances of it as in
SAMPLE_STRUCT ss1 = new SAMPLE_STRUCT();
SAMPLE_STRUCT ss2 = new SAMPLE_STRUCT();
and I want to send it to a class that have generic methods such as
byte[] ss1Array = sCopy.StructureToByteArray (ss1);
sCopy.ByteArrayToStructure (ss1Array, ref ss2);
where the interface is defined as
public byte[] StructureToByteArray(objec t obj)
{ ... }
public void ByteArrayToStructure(byte[ ] byteArray, ref object obj)
{ ... }
How do I get around the following errors:
The best overloaded method match for 'BD.EpiCenter.Utility.clsS tructCopy. ByteArrayT oStructure (byte[], ref object)' has some invalid arguments
Argument '2': cannot convert from 'ref TestStructCopy.Program.SAM PLE_STRUCT ' to 'ref object'
Is there a way to cast a typed variable to an obect/ref object such as
sCopy.ByteArrayToStructure (ss1Array, ref (object) ss2);
which obviously does not work or must I introduce a temporary object to pass into the method and copy out of after it completes as below which does work?
object ss2Obj = ss2;
sCopy.ByteArrayToStructure (ss1Array, ref ss2);
ss2 = (SAMPLE_STRUCT) ss2Obj;
say I have a declared type such as:
[StructLayout(LayoutKind.S
public struct SAMPLE_STRUCT
{
public UInt32 size;
public Boolean boolVar;
public Int32 intVar;
};
and have instances of it as in
SAMPLE_STRUCT ss1 = new SAMPLE_STRUCT();
SAMPLE_STRUCT ss2 = new SAMPLE_STRUCT();
and I want to send it to a class that have generic methods such as
byte[] ss1Array = sCopy.StructureToByteArray
sCopy.ByteArrayToStructure
where the interface is defined as
public byte[] StructureToByteArray(objec
{ ... }
public void ByteArrayToStructure(byte[
{ ... }
How do I get around the following errors:
The best overloaded method match for 'BD.EpiCenter.Utility.clsS
Argument '2': cannot convert from 'ref TestStructCopy.Program.SAM
Is there a way to cast a typed variable to an obect/ref object such as
sCopy.ByteArrayToStructure
which obviously does not work or must I introduce a temporary object to pass into the method and copy out of after it completes as below which does work?
object ss2Obj = ss2;
sCopy.ByteArrayToStructure
ss2 = (SAMPLE_STRUCT) ss2Obj;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Not if it's a value type (like a struct), you could have created it as a class instead and then you could have cast it to an object type.
ASKER