How to assign same object list but in different namespace.
list, list2
list = list2;
Cannot implicitly convert type
System.Collections.Generic.List<namespace1.MyData> to System.Collections.Generic.List<namespace2.MyData>
This sounds to me like a WCF proxy that has been generated and you want to reuse the existing class libraries instead of the proxy generated ones.
If this is the case, then see this answer or this answer.
Edit:
as a follow up to this, occassionally you may be in the position where you can't reuse the common class definitions (in the case of Silverlight you have to create a whole new assembly which may not be practical). If you are in this position, there is another option: the proxy generated classes are defined as partial, so you can extend them with a Clone() or Copy() method that returns the identical object from the other namespace, with the values copied over.
If the objects can be cast to each other, you can do this, but it is looping though the lists and making a copy, it's not a direct assignment.
var newList = oldList.Cast<NewType>().ToList();
Related
how is a tuple different from a class? instead of the following code, we can make a class with 3 fields and make objects from it. How is this Tuple different from that? Is it only reducing the code we write or does it have something to do with speed as well, given the fact that you can't change the items in a tuple.
Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1, "cat", true);
It saves you from having to define a new class with custom properties.
It does define equality by the value of the three items, which is something that a bare-bones class would not do without custom coding. That plus the fact that it's immutable makes it a reasonable candidate for a hash key in a Dictionary.
One drawback is that the properties are vanilla Item1, Item2, etc., so they don't provide any context to the values within them, where properties like ID, Name, Age would.
Tuple is a class. One that holds any data you want (in terribly named properties like Item1).
You should be making classes instead so your code is more readable/maintainable. Its primary function is as a "quick fix" when you want to associate pieces of data without making a class to hold them.
Tuples are in my opinion an invitation to bad data modeling. Instead of creating a proper model you get a generic object that can hold n item properties. The naming is very generic too.. Item1..ItemN
You use Tuples as a mean to pass data between method call without having to define a new class. Typically use to return multiple pieces of data from a method rather than use "out" parameters.
Keep in mind that out parameter cannot be use with async/await methods, this is where Tuples come in handy.
You probably want to define a class for your data if you code a reusable class library though. However, tuple is great in presentation layer.
I'm wondering if there is a way to do this inheritance situation in C#:
public class Item
{
public string Name { get; set; }
}
public class ItemExtended : Item
{
public int ExtendedProp { get; set; }
}
And let's say I have a method that returns objects of type Item:
public Item[] GetItems();
How can I make code like this run?
ItemExtended[] itemsExt = GetItems().Cast(i => (ExtendedItem)i).ToArray();
Where the cast wouldn't fail, the Name property value would be preserved and I would have an additional property ExtendedProp that I could access?
Edit (hopefully to clear some confusion)
In this situation the GetItems method would only ever return items of type Item. I was wondering if there was a casting method that could convert a base type to an inherited type such that all base member values are conserved (without the use of cloning).
If the runtime type of your object is Item, you can not cast it to an ItemExtended -- not unless there's a user-defined conversion that can create an ItemExtended from an Item. Note, however, that even then, you'll be creating a new instance of ItemExtended.
Inheritance in general doesn't work that way. In managed languages, downcasting only works if the runtime type of your object already is of the derived type. Instances of derived classes inherit all the data and behavior of their ancestor classes, but there's an ancestor doesn't have any knowledge of derived classes. Consider an example, where a derived class introduces a single new field. Firstly, the base class instance is smaller in size, so at the very least, a type cast would require allocating new memory. Second, you would have to decide between changing the runtime type of the original instance (which would be very weird indeed) or making a copy of the old data. The latter way would be very similar to the user-defined conversion scenario, except an user-defined conversion is explicitly invoked, and IMO better that way.
In unmanaged languages, you can of course make any arbitrary conversion you want -- but that just results in catastrophic failures if you do it wrong. In the example above, you would try to access the new field, but since it would not have been allocated for the instance, you would go beyond the boundaries of the object's memory space and access... whatever was in there, be it sensical or not.
If you want to introduce new behavior to existing classes, the C# way is via extension methods. Extension properties aren't there yet, and may never be, so you don't get the property syntax. You may or may not be able to live with that.
You may also find it interesting, that in XAML, the concept of attached properties sort of fits what you are trying to do: you can define arbitrary new properties for whatever -- but if you look at the implementation, what you are really doing is creating a dictionary that maps objects to their associated property values, and the XAML compiler sugarcoats this by making the markup look like you've added the properties to those objects.
You can use OfType instead of Cast:
ItemExtended[] itemsExt = GetItems().OfType<ItemExtended>().ToArray();
You're on the right track with a few adjustments,
use Select() instead of Cast() and
i as ItemExtended rather than (ItemExtended)i
This line should cast it correctly:
ItemExtended[] itemsExt = GetItems().Select(i => i as ItemExtended).ToArray();
I didn't find anywhere whether is possible to query from Db4o all objects implementing some generic interface
for example:
to query all objects implementing IList<T>, I tried:
var items = from IList<object> item in session
select item;
but this doesn't return all lists in database (only the ones which implements specificaly IList<object>)
Is there any way to do it other then query all objects from database, loop them and evaluate the object manually? (I would have to pass through milions of objects in this case)
Thank you
You want to query for all objects which are any instance of the IList<> type. Or other costume generic types.
In my opinion this is not possible at the moment. The reason is that db4o treats each instance of a List<> as its own type. So a List and a List are stored a two different types. This goes right down to the meta data storage in db4o, where those are stored separately. This also means that there not shared index for all instance of the different List<> types.
Btw in Java it is the other way around, all types of List<> are treated as the same type, since in Java generics are not reflected at runtime.
So, you basically need to go over all the different types of List<> yourself to get all instances.
For your own types I would create an abstract non generic class which the generic instance inherit. Then you can query for that and get all generic subtypes. Note that this doesn't work for interfaces, since db4o doesn't index or keep meta-infos for interfaces.
I'm trying to make a small application that can edit the data files from an earlier project. I have access to that projects "data classes" (pretty dumb classes whose main purpose is to expose it's (public) member variables) that can read/write to the files. All I have to do is make a GUI that can edit the different member variables that each data class have (preferably without modifying the data class) and I'm trying to figure out how to do this so that it will be easy to adapt for future changes/additions.
(I don't feel like I can assume that all member variables should be editable, might only be a selection of them).
All the data can be converted to/from strings (numbers and text) and I don't see much problem in generating textboxes and/or something like a DataGridView in the GUI, but I'm not sure as to how I would like to represent the data needed to generate those.
My first thought was to use a list with all variables for each data class. With each row in the list containing the name+description of the variable (for the GUI), a pointer to the variable in the data-class and perhaps some form of validation-function for different variables.
Store that list in a class that inherits the original data-class (and that implements an interface/abstract-class for any specific GUI-related functions (load/save etc.)).
The thing that makes me worry about this solution is just that I feel like this should be a somewhat common problem and I'm a bit rusty when it comes to OO and this solution smells like something I'd write if I had to do it in C.
There might even be a handy language construct, design pattern or something that is suitable but I don't know what to search for.
Does this approach even seem sensible?
Reflection is your friend in this case. Your data classes have a structure which can be explored using that class's Type. A Type is the base class for metadata concerning a class or structure, and includes methods to, for instance, get a list of all fields, properties and/or methods belonging to that class. The objects representing these class "members" can then be used to set or get field or property values, or invoke methods, given an instance of an object of that type.
A reflective algorithm can be designed to handle any object structure it is given, and it doesn't have to know those structures at compile-time unlike an algorithm based on static types. The downside? It's slow, and you get very little compile-time checking of your algorithm so it can fail at run-time in unexpected ways.
Here's something to get you started:
//statically set up an instance of some arbitrary object
MyClass myObject = new MyClass();
myObject.Field1 = "Hello";
myObject.Field2 = "World";
//This method is available on any object, and produces a Type representing the class definition
Type myType = myObject.GetType();
//C# also has a typeof() keyword that works when you have a static type and not an instance
myType = typeof(MyObject);
//Interrogate the Type instance to get its fields
FieldInfo[] fields = myType.GetFields();
//then, iterate through the fields to perform some (useful?) work.
//Here, we are outputting a list of paired field names and their current values.
//You will probably want to instantiate a Label and Textbox representing this value
//and show them on a Form.
foreach(FieldInfo field in fields)
Console.WriteLine(String.Format("{0}: {1}", field.Name, field.GetValue(myObject));
To handle editability, you will need some sort of record of what the user has permission to change and what they don't. If that information will never change from user to user, you can incorporate that information into the data class itself using attributes (which won't change the "interface" of the object; it'll still have all the same members, but those members will have additional metadata). You could also create another set of classes that implement an interface defining each one as a set of "field permissions" for its parent class, and then you can dynamically construct an instance of the "field permission" class with a Type instance representing your object definition, and knowledge of the name of the interface that field permission objects implement.
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#?