Please I have a class in c# whose main function is to return the types and objects as dictionary Over a service .
Is it possible to cast the Object sents over the WCF service in the front end.
I.e using reflection to get the type of an object from the types.ToString() and using the type to cast the objects.
NB the Class that returns the dictionary and my frontend are in different projects so different Namespaces:
Type repType = typeof(List <>).MakeGenericType(Type.GetType(EntityandTypes[entity]));
object rep = Assembly.GetAssembly(repType).CreateInstance(repType.FullName);
grdResult.ItemsSource =
e.Result.ToList().Cast<typeof(Type.GetType(EntityandTypes[entity]))>();
Note : EntityandTypes is a dictionary that contains Object and Their types.
What would you want to do with the cast values? Casts usually make a difference at compile-time whereas you're asking for something at execution-time.
If you can explain how you'd want to use this, we can probably help you design around it.
What sort of types are we talking about? classes? And what type of service is it?
If it is WCF, one option is to use type-sharing to use the same type at each end, but this abuses SOA a little bit. You can't cast a class to a very different type, but you can project into a different class. Various approaches for this are discussed here:
How to copy value from class X to class Y with the same property name in c#?
Related
I have a design right now where I want a dictionary that gives me some values that could be of different types. My idea would be to have some interface that would represent a potential value type so then I could implement the interface. My problem is that if I make a generic interface then I can't have the dictionary return multiple types of the interface. If I make variable interface methods, then I can't implement them properly in the wrapper classes. Does anyone have a good solution to have a dictionary with variable value types?
I have an existing base type and I would like to cast it to a derived type base upon the name of the type as a string, so something like this:
public void DoStuffInDerivedType(string derivedName) {
(base as Type.GetType(derivedName)).DoThisThing();
}
I'm pretty sure this can't be done but would be good to know for sure. Thanks
EDIT: I understand that I could construct the object using reflection from the type name but I want use an existing object. And also I know this is generally a bad idea. However I wanted to use this for a SpecFlow BDD Feature.
I'll repeat the advice that you probably don't need to do this, but because I have done this operation before:
Convert.ChangeType(ItemToCast, Type.GetType(stringNameOfType)))
Should work for you.
I don't think you need to cast it to the derived type. You should be able to cast it to the base type and use the shared interface (be it a base class or literal Interface) to perform whatever you want done.
If not, consider adding the behavior as an interface requirement so you can do it that way.
Finally: the one possibility where you'd need to do it this way is if you're overriding the casts...in which case I'm almost certain you can't do this without some heavy duty reflection.
This question already has answers here:
How do I use reflection to call a generic method?
(8 answers)
Closed 4 years ago.
I defined various classes like this:
public class Subclass<T> : BaseObject<T>, IObject, IObject<T> { ... }
BaseObject<T> contains all the functionality I need. IObject<T> allows it to be accessed between projects. IObject allows collections to be created: List<IObject>.
BaseObject<T> and IObject<T> have a property T Value;
So I have
public class BaseObject<T> // T is double, int, decimal, long, short, int - in fact anything enumerable
: IObject, IObject<T>
{
[...]
T Value;
[...]
}
The problem I am trying to solve is how to unpack this by type T.
I want to write this function but don't know how in C#:
public void DoProcessing(List<IObject> objectsToBeProcessed)
{
foreach(dynamic singleObject in objectsToBeProcessed)
{
Type unpackedType = [somehow retrieve the type]
BaseObject<unpackedType.GetType()> unpackedObject = [do some kind of conversion of singleObject];
ProcessorClass<unpackedType.GetType()> processor = new ProcessorClass<unpackedType.GetType()>();
processor.Process(unpackedObject);
}
}
I'm finding this quite hard to put into words but I hope that this explanation gets the idea across. Basically I lose the type information when I build the List<IObject> and I need it back later on when I pass it across into another assembly. I want a single central DoProcessing method that can then delegate by type to instances of generics.
How can I get the type information back?
I understand that generics need a type known at compile-time. But this is situation where you only know the type at runtime. The dynamic keyword allows the collection to be iterated, but I haven't found a way to create the bit inside the loop.
Or should I just force everything to a double in BaseObject and then cast it back locally in some way?
I'm a bit lost on this and feel I am missing something obvious. Any ideas welcome.
POSTSCRIPT - CLARIFICATION
The purpose of this is to separate the code-base into two assemblies:
The assembly with BaseObject<T> allows customers and third parties
to write their own business logic which we don't need to see. They
simply subclass the BaseObject into their own code.
The assembly with IObject & IObject<T> contains generic business
logic that we are creating.
We need this separation in so customers can develop their own libraries of code without having to submit it to us. They just send us a list of List<IObject> and we do the rest, calling their subclasses back as necessary.
Surely it is possible!
ALTERNATIVELY
Can anyone suggest a better architectural solution to the two assembly solution I have described i.e. concrete classes in customer code assembly & abstract/interfaces in our framework assembly.
SOLUTION
OK so I've found a simpler solution. Late-binding via Reflection is doable but is hard to implement with my nuanced object model.
Instead, I have replaced the generic type T and implemented a property which is an enum of
public enum ValueType
{
Double,
Boolean,
Integer,
...
}
I then implement overloaded constructors, added this property to the non-generic interface IObject and have removed the generic interface IObject<T> as it's no longer needed.
Returning the value as double or bool is then handled by
public double AsDouble();
public bool AsBoolean();
public int AsInt();
...
in the interface.
It's not elegant or theoretically pure but it means I don't lose type information and can treat instances all the same. I just unpack the ValueType and choose different behaviour programmatically. It also avoids using the dynamic keyword as all values are implemented as double so looping is easy to implement.
On the plus side I have removed a lot of constraints on generics as they were needed up the inheritance hierarchy. It was getting really complicated and the compilation errors were getting too difficult to unravel.
It feels a bit unsatisfactory from a purist perspective, but MongoDB does something similar so that's good enough for me.
I do feel however that C# is "unfinished" in this area and needs a way to upcast or downcast more easily. It's just such an obvious thing to add.
Maybe the Reflection can be wrapped up somehow to make it transparent to the programmer.
Over-engineering, pragmatism and purism. These are the things that weigh on me...
This should be enough to return the type of the object inside your loop:
Type unpackedType = singleObject.GetType();
I'm using C# dynamic keyword and I've got an instance where I need to set a property value.
However, this property requires a type that I have no access to since I generated an assembly in memory from WSDL.
How can I create the property instance dynamically?
There is no such thing as a property instance; there is:
an instance of an object
which has members (which may be dynamic in this case)
to which you want to assign a value
If you don't know the type of the value in advance, you will need to create the object with a combination of reflection (from the Type) and perhaps dynamic. The latter depends on whether the underlying object is actually dynamic, vs being a regular type exposed via the dynamic API. Likewise, whether you can assign the value to the property via reflection - or whether you must use the dynamic API - depends on the same. Fortunately, there are tools like FastMember which allow you to access arbitrary members (with names known only at runtime, not compile-time) identically for the two cases. So if the scenario is complex, maybe give that a whirl.
I have a VB background and I'm converting to C# for my new job. I'm also trying to get better at .NET in general. I've seen the keyword "T" used a lot in samples people post. What does the "T" mean in C#? For example:
public class SomeBase<T> where T : SomeBase<T>, new()
What does T do? Why would I want to use it?
It's a symbol for a generic type parameter. It could just as well be something else, for example:
public class SomeBase<GenericThingy> where GenericThingy : SomeBase<GenericThingy>, new()
Only T is the default one used and encouraged by Microsoft.
T is not a keyword per-se but a placeholder for a generic type. See Microsoft's Introduction to Generics
The equivalent VB.Net syntax would be:
Public Class SomeBase(Of T As {Class, New}))
A good example of another name used instead of T would be the hash table classes, e.g.
public class Dictionary<K,V> ...
Where K stands for Key and V for value. I think T stands for type.
You might have seen this around. If you can make the connection, it should be fairly helpful.
That would be a "Generic". As people have already mentioned, there is a Microsoft explanation of the concept. As for why the "T" - see this question.
In a nutshell, it allows you to create a class/method which is specialized to a specific type. A classical example is the System.Collections.Generic.List<T> class. It's the same as System.Collections.ArrayList, except that it allows you to store only item of type T. This provides type safety - you can't (accidentally or otherwise) put items of the wrong type in your list. The System.Collections.Generic namespace contains several other different collection types which make use of this.
As for where you could use it - that's up to you. There are many use-cases which come up from time to time. Mostly it's some kind of a self-made collection (when the builtin ones don't suffice), but it could really be anything.
Best way would be to get yourself familiar with "Generics", many resources on the web, here's one
T is not a keyword but a name, could be anything really as far as I know, but T is the convention (when only one type is needed, of coruse)
The T is the name for the type parameter in a generic class. It stands for "Type" but you could just as well call it "Alice."
You use generics to increase reusability in a type-safe manner without needlessly duplicating code. Thus, you do not need to write classes for ListOfIntegers, ListOfStrings, ListOfChars, ListOfPersons and so on but can instead write a generic class List<T> and then instantiate objects of types List<Int32>, List<string>, List<char> and List<Person>. The compiler does the work for you.
It means "any class". It could be "B", "A", whatever. I think T is used because of "Template"