473,395 Members | 1,411 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Dynamic cast with generics

Hi,
i'm trying to solve the next problem ...

public class BaseType {...}
public class DerivedType : BaseType { ... }

public abstract class BaseClass
{
public abstract Type getGenericType();
}

public class DerivedClass<TheType: BaseClass where TheType : BaseType
{
public override Type GetGenericType()
{
return typeof(TheType);
}
}
.. . .
public class Example
{
public static void Main()
{
. . .
DerivedClass<DerivedTypeTransferedObject = new
DerivedClass<DerivedType>();
TheCall(TransferedObject);
}
public void TheCall(BaseClass AnObject)
{
Type GenericType = AnObject.GetGenericType();

// PROBLEM... this is what i tried to .. .
TheProcess(AnObject); // Cannot because C# doesn't suppor variance
for generic types
TheProcess((TheClass<GenericType>) AnObject); // Cannot because
GenericType is a variable, not a type
}

public void TheProcess(DerivedClass<BaseTypeValue)
{
. . .
}
}

----------------
So... I need to cast a reference from an ancestor type to a derived type
dynamically.
Maybe Reflection has the solution?
Any help will be appreciated.
Néstor.
Jan 29 '07 #1
3 7089
If you are using generics, then *use* generics. For instance:

public void TheCall<T>(T AnObject) where T : BaseClass {...}
public void TheProcess<T>(DerivedClass<TValue) where T : BaseClass
{...}

As you say, another option is reflection - but this should be a last
ditch solution. Is there a (good) reason why you can't use the above?
As the answer to this may influence the best answer...

Marc
Jan 29 '07 #2
....the problem is that I don't know that is the derived type used.
The scenario is the following...
I have a namespace with types and classes that defines a business model.
Then, in another namespace, I have the presentation layer where I only need
to know the base types just to show values thru polymorphism (i.e:
AnObject.ToString()).
In other words, at the caller level there is irrelevant any detailed
(derived) information, but still there is need to reference the objects...
how?.
Thanks,

Néstor.
"Marc Gravell" <ma**********@gmail.comescribió en el mensaje
news:Ow**************@TK2MSFTNGP03.phx.gbl...
If you are using generics, then *use* generics. For instance:

public void TheCall<T>(T AnObject) where T : BaseClass {...}
public void TheProcess<T>(DerivedClass<TValue) where T : BaseClass {...}

As you say, another option is reflection - but this should be a last ditch
solution. Is there a (good) reason why you can't use the above? As the
answer to this may influence the best answer...

Marc

Jan 29 '07 #3

Then yes, reflection may be your best bet. In this scenario I would
use GetType() and MakeGenericMethod to invoke the method (as above) so
that my reflection is limited to the invoke step, rather than
throughout.

Watch for wrap: <http://msdn2.microsoft.com/en-us/library/
system.reflection.methodinfo.makegenericmethod(VS. 80).aspx>

Marc

Jan 29 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: adrian | last post by:
hi all this is my first post to this group, so pls bear with me while i try to make some sense. i am trying to create a sproc which uses dynamic sql to target a particuar table eg. '.' and...
1
by: andrew queisser | last post by:
I've been trying to dynamically create a class DevT that's derived from a generic base GenBase<T>. It doesn't seem to work. I'm attaching a code sample below that illustrates the problem. ...
11
by: Vincent Finn | last post by:
Hi, Is there any way of having a strongly typed dynamic array in C#? ArrayList requires you to cast every time you want to access an element object isn't dynamic I have resorted writing a...
17
by: Hazz | last post by:
In this sample code of ownerdraw drawmode, why does the '(ComboBox) sender' line of code need to be there in this event handler? Isn't cboFont passed via the managed heap, not the stack, into this...
6
by: Philipp Schumann | last post by:
Hi, I have a need for "dynamic type casting": in other words, in a "MyConvert" method I get passed an Object "value" and a Type "type" and the method should attempt to convert value into type. ...
5
by: Jimp | last post by:
Why can't I cast List<MyObject> to ICollection<IMyObject>. MyObject implements IMyObject, and of course, List implements ICollection. Thanks
2
by: =?Utf-8?B?bmV0dGVsbGVjdA==?= | last post by:
I have a simple situation in which I want to use generics along with dynamic type assignment. Following code snippet can explain in more detail But I am unable to do that will anybody help me why?...
5
by: taumuon | last post by:
I've got an object, Person, that supports IEquatable<Person>. It implements bool Equals(Person obj) as well as overriding bool Equals(object obj) I've got a container type that holds a member...
4
by: =?Utf-8?B?SGF5U2VlZA==?= | last post by:
Is there some way to use Generics in dynamic code using the Type.GetType("MyClassName") as an argument? List<Type.GetType("MyClassName") oList = new List<Type.GetType("MyClassName") > ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.