I have an array of objects looking like this
public class ViewFilterData
{
public string Table { get; set; }
public string Field { get; set; }
public string Value { get; set; }
}
Due to calling function in separate dll, I need to pass this array as object[]. The above class is defined in both sections.
Project compiles, however when I try to cast each object in the array to above class, I get an invalidCastException, indicating that it "magically" know the originally class and refuse to cast it to the new one even though they are verbatim identical. Do I need to use reflection and create a new class marshalling over the array object by object and attribute by attribute? Or is there a simpler faster way? Thought about using scructs, however would rather not if possible.
"Unable to cast object of type 'Original.ViewFilterData' to type SeparateDLL.ViewFilterData'."
I call the function like this
var dt = oRepository.Page((object[])oDataRequest.Filters.ToArray())
and define it like this
public DataTable Page(object[] Filters)
Same name doesn't mean, they're of the same types. .NET cannot magically infer that.
for small objects, just write a quick LINQ query:
var separateDllFilters = oDataRequest.Filters.Select(of => new SeparateDLL.ViewFilterData
{
Table = of.Table,
// so on
}).ToArray();
however, if all the fields are same, (or even if they're not) you can use tools like AutoMapper to transform them easily.
typically, this is the order of solutions:
quick LINQ queries.
Extension methods to map the types.
Tools like AutoMapper
the solution you choose depends on factors like, how often you do this, how many callers need this, etc.
The above class is defined in both sections.
This is not valid in C#, each class is distinct from all other classes.
If you want to pass data between libraries you must use consistent types. The most popular method is to use a base library.
Related
Problem
I call different webservices which returns json strings. I parse these strings to custom objects and save them in a "result class" called APIResult. For instance, one webservice returns a list OBJ1, another returns OBJ2, and sometimes two or more objects are returned as well. The result class is returned to the method calling it with the objects and a boolean indicating whether the request was succesful.
This works, but when I have to call many different webservices the class gets ugly. Right now I have 7 properties like OBJ1, OBJ2, List, List and so on. To avoid adding more properties to the APIResult class I want to redesign it to be more flexible, but I'm not sure what is the best approach.
Ideas
Generics seems to be a good idea. I could initialize my class with new APIResult(ObjectType) and then have one or more properties T Data1. Still a bit ugly to have three properties T Data1, T Data2, T Data3. I am also unsure if I can parse the objects from json to a generic type without reflection and if that would slow things down.
Do you have any suggestions?
Separate the result state from the actual data.
As you suggested, generics are a useful tool for this. Create a result state class that encapsulates the success/failure logic and (in the case of success) provides access to the data.
This could look something like this:
public class ApiResult<T>
{
public bool Success { get; }
public T Dto { get; }
public ApiResult(bool success, T dto)
{
Success = success;
Dto = dto;
}
}
Now design the data classes as simple property bags without any logic. Their only purpose is to define what data is returned from a specific web service. Also, do not try to build deep inheritance hierarchies. Adding the same property to two different DTOs is fine.
public class Dto1
{
string PropertyA { get; set; }
string PropertyB { get; set; }
}
public class Dto2
{
string PropertyA { get; set; }
string PropertyC { get; set; }
}
With this, you are now able to define proxies for the web services you call. A proxy interface could look like this:
public interface ISomeServiceProxy
{
ApiResult<Dto1> GetTheThing(string someParam);
}
In the implementation of this interface you will want to use JSON.NET to deserialize the response into a Dto1 and wrap it in a ApiResult.
Also, you probably want to make the proxy use async. I left that out in these examples, converting them is straight-forward.
There are few things to consider here
Do you need an APIResult class? What are you going to do with it? If you have a well documented REST api (say an odata api) then the response is well described and you can verify that the response you get is what you need. Otherwise what are you going to do if it doesn't match?
if you are just going to parse it into your model you might even consider the generic JObject to hold your response. Then you can check for properties/subobjects on this JObject. You could even pass this into the (newtonsoft) json serializer and have the calling method say what it should look like.
what is the business meaning of your response? Result is always a hard name. However if you you have properties like FirstName, LastName, AddressList, etc then it becomes a lot nicer.
I've read a number of articles including this one on the subject of Empty or 'marker' interfaces. I have concluded that I cannot use custom attributes in my case as I need to be able to include the instance of a class to another method and, as these classes have nothing in common, I have no option but to use a 'marker' interface.
As an example, I might have
public class Foo
{
public int Id {get;set;}
public string Name {get;set;}
}
public class Bar
{
public Guid Identifier {get;set;}
public DateTime DueDate {get;set;}
}
and I need to pass them to a method in another class and because there may be many different types that need to be passed to the method, I've defined it like this...
public void MyMethod(IMyInterface model)
{
// Do something clever here
}
And All I've had to do to make this work is to 'implement' IMyInterface on Foo and Bar.
So to the question. I now find I need to call my MyMethod() method with an anonymous type created from a LINQ statement, so I tried this ...
var data = <Some Complex LINQ>.Select(a=> new { AString = a.Value1, ADecimal = a.Value2});
MyClass.MyMethod(data);
Sadly, I get the following compile-time error:
Error 202 Cannot convert type 'AnonymousType#1' to
'IMyInterface' via a reference
conversion, boxing conversion, unboxing conversion, wrapping
conversion, or null type conversion
Now, I know I could create a local class and use that in the same way as I have my standard classes, but my requirements mean that I'm going to have a lot of these LINQ queries in my up-coming set of work so, if possible, I'd like to find a solution that allows me to use Anonymous Types.
Does anyone know of a solution or workaround for the error I'm getting?
Say I have a bunch of classes that implement an interface:
public interface IBuilding
{
string WhatAmI();
}
Class house:IBuilding
{
string Ibuilding.WhatAmI(){return "A House";}
}
Class Skyscraper:IBuilding
{
string Ibuilding.WhatAmI(){return "A Skyscraper";}
}
Class Mall:IBuilding
{
string Ibuilding.WhatAmI(){return "A Mall";}
}
And then I want to dynamically choose what to instantiate the class:
enum buildingType { house, Skyscraper, Mall };
string someMethodOrAnother()
{
string building= textboxBuildingType.Text;
Ibuilding MyBuildingClass;
buildingType UserSelectedClass = (buildingType) Enum.Parse(typeof(buildingType), building);
if (Enum.IsDefined(typeof(buildingType), UserSelectedClass) )
{
MyBuildingClass = (some code that dynamically creates a class instance);
}
else
{
MyBuildingClass = new house();
}
return MyBuildingClass.WhatAmI;
}
Now I could do this in a switch statement, but I thought I had found a more elegant technique. Or is the whole idea of using an interface wrong? Perhaps I need a delegate instead?
In general, I would use a Dictionary with Activator.CreateInstance:
Dictionary<buildingType, Type> typeMap = new Dictionary<buildingType, Type>()
{
{ buildingType.House, typeof(House) }
}
IBuilding building = (IBuilding)Activator.CreateInstance(typeMap[userSelection]);
If this were WPF, you could use a converter to do this directly from the view to the view model.
If I understand what you're trying to do correctly, there are several ways to go about this but at the end of the day you'll have to have some logic that picks one particular type from a list of available types.
Some options (not an exhaustive list):
Use reflection to inspect your assemblies and determine what types implement the interface you want.
Use dependency injection (like LightInject) to do the assembly inspection for you and give you a list of types you can instantiate. DI libraries have various features to control how to discover types. This is a very flexible solution and the work is done for you.
Use an XML file (or other file format) to describe types that can be used. This is not very flexible but it allows you to list the types you want to be available regardless of what's in the assemblies. (Obviously, you can't make a non-existent type available but you can hide existing types without recompiling the code.)
At the end, you'll end up with a list of types that implement the interface you need. With the list you have to implement some kind of logic to actually pick one particular type that you'll instantiate - this logic is specific to your application (maybe pick the type based on a list in a listbox, etc.): no one can tell you how to do this.
Once you pick the type, you can just use Activator.CreateInstance() to create an instance of the type you picked. Alternatively, if you use LightInject, you can ask the library to return an instance of the specific type for you.
I have a class which is has tons of properties. Most of them are of custom types. I want to get all those properties, type of whose interface is same.
Public class abc:IamLegend
{
few properties
}
public class def:IamLegend
{
few properties
}
public class on_which_iamworking
{
public abc propabc{ get; set; }
public def propdef{ get; set; }
public someothertype propother{ get; set; }
}
I want something which returns propabc and propdef.
I know how to do it using reflection, but I am looking for another way.
I am working on c# 4.0
Thanks
I am afraid that this is not possible at runtime without using reflection. That's what reflection is designed for.
The main problem of reflection is that it is slow. If you don't want to use reflection only because of it's slowness, you could make caching of your property list in some static property or class. I used this tecknique widely in similar problems and there wasn't any problems with perfomance.
If you have holy war against reflection, you could create a special util that parses C# file (or builds your prokects, loads output assembly and use reflection, but only before build, not in run-time), finds needed properties and writes it into autogenerated file (maybe also C# code file) as static-class array-property initializer. And call that util on pre-build event of your project. Then you'll get all needed properties completely without reflections =) (but I wouldn't do that)
Well, there's two ways:
1/
return new List<string> { "propabc", "propdev" };
2/ Reflection :P
If you need to retrieve the list of properties many times and are afraid of the performance impact, compute the list only once and store it in a static property (as the list of properties of a class won't change during runtime).
There is an alternative approach for components. It is TypeDescriptor for classes that implement IComponent. I believe that is used by WPF.
I need some help with a design issue I'm having. What I try to achieve is this:
I have a main class called Document. This Class has a list of Attribute classes. These Attribute classes have some common properties such as Identity and Name, but they differ in one property I call Value. The Value type is different for each different Attribute class and be of type string, integer, List, DateTime, float, List and also classes that consists of several properties. One example would be a class I would call PairAttribute that have 2 properties: Title and Description.
What I try to achieve is type safety for Value property of the Attribute child classes and that these child classes should be able to be added to the Attribute list in the Document class. I could have made only one Attribute class that have a Value property of type object and be done with it, but that is exactly what I try to avoid here.
The common properties (Identity and Name) should be placed in a base class I guess, lets call that AttributeBase class. But I want to have a child class, say StringAttribute, where the Value property is of type string, a IntegerAttribute class where the Value property is of type Integer, a StringListAttribute where the Value property is of type List, a PairAttribute class where the Value is a class with several properties, etc
Do you know how I can implement this? Is this a solution I should go for at all or is it a better ways of solving this type safety issue? I would appreciate code examples for clarification:)
You don't specify a language, but the feature described by the term "generics" (as used by Java and C#) is often called "parametric polymorphism" in other languages (like ML and Haskell). Conversely, the common meaning of "polymorphism" in Java and C# is actually more precisely called "subtype polymorphism".
The point is, whether you are using subtype polymorphism or parametric polymorphism, either way your problem calls for polymorphism, so I think you're on the right track.
The question really boils down to: when is parametric polymorphism better than subtype polymorphism? The answer is actually quite simple: when it requires you to write less code.
So, I'd suggest you prototype both approaches, and then see which one leads to simpler, easier to understand code. Then do it that way.
You may pass with a generic Attribute instead of inheritance/method polymorphism, but you will need to store them in some list and for that you will need an interface, because datastores in .Net cannot be a collections of undefined generic types, and if you would define them you would not be able to mix types inside:
public interface IAttribute {
string Identity { get; set; }
string Name { get; set; }
T GetValue<T>();
}
public class Attribute<T> : IAttribute
{
public string Identity { get; set; }
public string Name { get; set; }
public T Value { get; set; }
public Tret GetValue<Tret>() {
return (Tret)(Object)Value;
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
List<IAttribute> lst = new List<IAttribute>();
Attribute<string> attr1 = new Attribute<string>();
attr1.Value = "test";
Attribute<int> attr2 = new Attribute<int>();
attr2.Value = 2;
lst.Add(attr1);
lst.Add(attr2);
string attr1val = lst[0].GetValue<string>();
int attr2val = lst[1].GetValue<int>();
}
}
The (Tret)(Object) actually does not change type, it only boxes T and the (Tret) unboxes the value without using middle variables. This will of course fail if you miss the right type when calling GetValue<type>(). Even if compatible types are sent like Value is integer and you do GetValue<double>() -> because unboxing an integer into a double is not allowed.
Boxing/Unboxing is not as fast as casting but it ensures type safety is preserved, and there is at my knowledge no way to use generics with an compile time known interface in some other way.
So this should be type safe... and without a lot of code.