Is there a way to take an interface, say:
/// <summary>
/// Interface containing operators which operate on T
/// </summary>
public interface IScalarOperators<T>
{
// Adds two T objects
IOperateScalar<T> OperatorAdd { get; }
// Subtracts two T objects
IOperateScalar<T> OperatorSubtract { get; }
// Multiplies two T objects
IOperateScalar<T> OperatorMultiply { get; }
}
// Class containing all the Scalar operators for a given T
class ScalarOperators<T> : IScalarOperators<T>
{
public IOperateScalar<T> OperatorAdd { get; private set; }
public IOperateScalar<T> OperatorSubtract { get; private set; }
public IOperateScalar<T> OperatorMultiply { get; private set; }
private ScalarOperators(IOperateScalar<T> add, IOperateScalar<T> subtract, IOperateScalar<T> multiply)
{
this.OperatorAdd = add;
this.OperatorSubtract = subtract;
this.OperatorMultiply = multiply;
}
public static ScalarOperators<bool> CreateBool()
{
return new ScalarOperators<bool>(new AddBool(), new SubtractBool(), new MultiplyBool());
}
public static ScalarOperators<int> CreateInt()
{
return new ScalarOperators<int>(new AddInt(), new SubtractInt(), new MultiplyInt());
}
// METHOD I WANT TO ADD
public static ScalarOperators<T> Create()
{
// if T == bool
// return CreateBool()
// if T == int
// return CreateInt()
// else (no definition available for T)
// return null
}
// I tried something like below, but it didn't work...
public static ScalarOperators<T> Create<T>() where T: bool
{ return CreateBool(); }
public static ScalarOperators<T> Create<T>() where T : int
{ return CreateInt(); }
public static ScalarOperators<T> Create<T>()
{ return null; }
}
Notice, I'd like a generic Create method which creates the correct set of operators, but I'm not sure how to do it.
I'd like to use it to remove the parameter from this method:
public static IMatrix<T> Add<T>(this IMatrix<T> matrix, IMatrix<T> other, IScalarOperators<T> operators)
{
JoinCells<T> joiner = new JoinCells<T>();
return joiner.Join(matrix, other, null, operators.OperatorAdd);
}
becomes
public static IMatrix<T> Add<T>(this IMatrix<T> matrix, IMatrix<T> other)
{
JoinCells<T> joiner = new JoinCells<T>();
return joiner.Join(matrix, other, null, ScalarOperators<T>.Create().OperatorAdd);
}
Thanks for any help! Mainly, I just don't want to have to pass the scalarOperator object to the extension method, I'd prefer to have a 'default' since it is unlikely that the ScalarOperators will change for any T that is defined.
i suggest making a factory of IScalarOperators instead of static class ( if your really need it to be static you could access it by static field ).
you could register them at app startup and get them by this example metod:
public IScalarOperators<T> Create<T>()
{
// check if exists in dictionary
return (ScalarOperators<T>)dict[typeof(T)];
}
dict will be of type Dictionary.
The adventage is that you could add new IScalarOperators during application grow only by creating new implementing class and registering it in factory, casting is a drawback. Also you will have better seperation of concerns and ( in my opinion ) cleaner code.
What you need to do is get the type of T.
Your Create method could be like this:
public static ScalarOperators<T> Create()
{
Type type = typeof(T);
if(type == typeof(bool))
return CreateBool()
if(type == typeof(int))
return CreateInt()
else
return null
}
There are a few things happening here that I think should be addressed. You're trying to segregate your custom operators from the types that they operate on, which is confusing, and you're trying to take the very broad concept of generics and then specialize them.
For the first one, you're always going to use the same operators for the same type (at least, you're never going to try and use bool operators on an int type). There's no reason to complicate things by having a separate class for them. For the latter, generic classes and generic methods are meant to work the same for any given T. Granted, you very well could get the typeof(T) in your static factory method and compare against that for several specific cases, and then you'll have to change that for every new T that you want to handle because of this overly complicated generic operand structure.
I would recommend creating a generic interface for your operands and then implementing a wrapper for those types instead. For example, int can be wrapped like this.
public interface IScalarOperators<T>
{
IScalarOperators<T> Add (IScalarOperators<T> rightSide);
IScalarOperators<T> Subtract (IScalarOperators<T> rightSide);
IScalarOperators<T> Multiply (IScalarOperators<T> rightSide);
T Unwrap();
}
public interface IMatrix<T> where T : IScalarOperators<T> { /* whatever */ }
public class CustomInt : IScalarOperators<CustomInt>
{
private readonly int number;
public CustomInt(int number) { this.number = number; }
public CustomInt Unwrap() { return this; }
public IScalarOperators<CustomInt> Add(IScalarOperators<CustomInt> rightSide) { return new CustomInt(number + rightSide.Unwrap().number); }
public IScalarOperators<CustomInt> Subtract(IScalarOperators<CustomInt> rightSide) { return new CustomInt(number - rightSide.Unwrap().number); }
public IScalarOperators<CustomInt> Multiply(IScalarOperators<CustomInt> rightSide) { return new CustomInt(number * rightSide.Unwrap().number); }
}
At that point, you can operate on an IMatrix<CustomInt> through the IScalarOperators<T> interface and perform any exposed operations you want. As a rough example, assuming you have an exposed accessor called array, you could say IScalarOperators<T> result = matrix.array[0, 0].Add(matrix.array[0, 1]); and get a representation back of adding the two together. You could then perform any further operations on that, and so on.
Related
I have the following type hierarchy:
public interface IDocument<TItem>
{
IEnumerable<TItem> Query(string query);
string FileName { get; }
}
public abstract class Document<TDocument, TItem> : IDocument<TItem>
{
public abstract IEnumerable<TItem> Query(string query);
public string FileName { get; private set; }
protected readonly TDocument _content;
}
public class DocumentX : Document<string, int>
{
...
}
public class DocumentY : Document<string, TypeOther>
{
...
}
and so on...
And I want to create a factory method, like this:
private IEnumerable<IDocument<T>> Factory<T>()
where T : IDocument<T>
{
yield return new DocumentX();
yield return new DocumentY();
}
The goal is to have a factory method, that will return a collection with different concrete implementations, which are derived from a common interface (IDocument)
But a compiler error raise:
"Cannot implicitly convert type 'DocumentX' to 'IDocument'. An explicit conversion exists (are you missing a cast?)"
What did I miss?
This is a misuse of generics. If your method is generic, it should not decide what T is. The caller decides what T is. Right now, your Factory method is making assumptions about what T exactly is. This shows that Factory should not be generic.
What you are trying to say, is something like
Hey, caller of Factory, I'm going to return a bunch of IDocument<T>s, but you don't know what the T of each one is going to be.
That's what happens when you put both a DocumentX and a DocumentY into an IEnumerable. Imagine that I'm consuming the IEnumerable returned by Factory. I won't know what kind of document each element I get is. i.e.
foreach (IDocument<???> document in Factory()) {
??? queryResult = document.Query("some query");
}
I will have no idea what I should put in ???.
Well actually, I do have a little idea of what Query would return. If I write:
foreach (IDocument<object> document in Factory()) {
object queryResult = document.Query("some query");
}
That would work, since everything can be converted to object. So we just need to write an AnyDocument class that conforms to IDocument<object>:
public class AnyDocument : IDocument<object> {
public string FileName { get; private set; }
private Func<string, IEnumerable<object>> query;
public IEnumerable<object> Query(string query)
{
return this.query(query);
}
private AnyDocument() { }
// this is used to convert an `IDocument<T>` to an AnyDocument
public static AnyDocument FromDocument<T>(IDocument<T> document) {
var doc = new AnyDocument();
doc.FileName = document.FileName;
doc.query = s => document.Query(s).Cast<object>();
return doc;
}
}
And now you can declare Factory like this:
private IEnumerable<IDocument<object>> Factory()
{
yield return AnyDocument.FromDocument(new DocumentX());
yield return AnyDocument.FromDocument(new DocumentY());
}
This whole thing could have been a lot simpler if the T in IDocument<T> is limited to reference types, i.e. no IDocument<int> like in DocumentX. Because then you can just use generic variance:
// just add the word "out"
public interface IDocument<out TItem>
Actually, I would say you should do this regardless, because then you can directly return the document objects if T is a reference type, and use AnyDocument only if T is a value type:
private IEnumerable<IDocument<object>> Factory()
{
yield return AnyDocument.FromDocument(new DocumentX());
yield return new DocumentY(); // let's say "OtherType" is a reference type
}
Try:
private IEnumerable<IDocument<T>> Factory<T>() where T : IDocument<T>, class
{
yield return new DocumentX() as T;
yield return new DocumentY() as T;
}
By casting the DocumentX, DocumentY as T you ensure all of them are at least of type IDcoument<T>, if not the class T which implements IDocument<T>.
I am trying to create a Generic interface where the parameter type of one of the methods is defined by the generic
EDIT
I've changed the question slightly after realising I have probably confused matters by specifying a type parameter in the Factory creation method. What I have is two types of API calls that I need to make to a 3rd party API. The first retrieves a record from the API using an Id that is an int. The second also retrieves a record from the API but the Id is a string (guid). I have a class for each record type (ClientEntity and InvoiceEntity) that both implement a Generic Interface where I pass in the Id type
This is the Interface in which I declare a Method with an id Parameter
public interface IGeneric<TId>
{
void ProcessEntity(TId id);
}
I implement the interface in a couple of classes, one sets the id to be an int, the other a string.
public class ClientEntity: IGeneric<int> // Record with Id that is an int
{
public void ProcessEntity(int id)
{
Console.WriteLine(id);
// call 3rd party API with int Id
}
}
public class InvoiceEntity: IGeneric<string> // Record with Id that is a string (guid)
{
public void ProcessEntity(string id)
{
Console.WriteLine(id);
// call 3rd party API with string Id
}
}
What I would like to know is how do I use this within a factory pattern?
public static class GenericFactory
{
public static IGeneric<WhatGoesHere> CreateGeneric(string recordType)
{
if (recordType == "Client")
{
return new ClientEntity();
}
if (type == "Invoice")
{
return new InvoiceEntity();
}
return null;
}
}
The objective is to use the factory to instantiate the correct class so that I can call the ProcessEntity method
EDIT
I don't want to have to pass in the Generic type to the factory method because the class that is created by the factory should handle that. When I create the object, I don't know what Id type is required, I want the factory to handle that
e.g.
var myGeneric = GenericFactory.CreateGeneric("Client");
myGeneric.ProcessEntity("guid")
or
var myGeneric = GenericFactory.CreateGeneric("Invoice");
myGeneric.ProcessEntity(1234)
I hope that makes sense
You should be able to do something like this:
public static class GenericFactory
{
public static IGeneric<T> CreateGeneric<T>()
{
if (typeof(T) == typeof(string))
{
return (IGeneric<T>) new GenericString();
}
if (typeof(T) == typeof(int))
{
return (IGeneric<T>) new GenericInt();
}
throw new InvalidOperationException();
}
}
You would use it like this:
var a = GenericFactory.CreateGeneric<string>();
var b = GenericFactory.CreateGeneric<int>();
Note that this uses a strongly-typed call rather than passing in the type name as a string (which may or may not be what you actually want).
If instead you want to pass a string for the type name, you will have to return an object because there is no way to return the actual type:
public static object CreateGeneric(string type)
{
switch (type)
{
case "string": return new GenericString();
case "int": return new GenericInt();
default: throw new InvalidOperationException("Invalid type specified.");
}
}
Obviously if you have an object you would normally have to cast it to the right type in order to use it (which requires that you know the actual type).
Alternatively, you could use reflection to determine what methods it contains, and call them that way. But then you'd still need to know the type in order to pass a parameter of the right type.
I think that what you are attempting to do here is not the right approach, which you will discover once you start trying to use it.
Hacky solution: Use dynamic
Nevertheless, there is one way you can get something close to what you want: Use dynamic as follows (assuming that you are using the object CreateGeneric(string type) factory method from above):
dynamic a = GenericFactory.CreateGeneric("string");
dynamic b = GenericFactory.CreateGeneric("int");
a.ProcessEntity("A string");
b.ProcessEntity(12345);
Be aware that dynamic uses reflection and code generation behind the scenes, which can make the initial calls relatively slow.
Also be aware that if you pass the wrong type to a method accessed via dynamic, you'll get a nasty runtime exception:
dynamic a = GenericFactory.CreateGeneric("string");
a.ProcessEntity(12345); // Wrong parameter type!
If you run that code, you get this kind of runtime exception:
Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'ConsoleApplication1.GenericString.ProcessEntity(string)' has some invalid arguments
at CallSite.Target(Closure , CallSite , Object , Int32 )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)
at ConsoleApplication1.Program.Main() in D:\Test\CS6\ConsoleApplication1\Program.cs:line 71
Usually for that Factory using some DI container (DI can be useful, for example, when GenericInt or GenericString has dependencies), but to demonstrate just Idea how you can resolve this:
void Main()
{
GenericFactory.CreateGeneric<int>();
GenericFactory.CreateGeneric<string>();
}
public static class GenericFactory
{
private static Dictionary<Type, Type> registeredTypes = new Dictionary<System.Type, System.Type>();
static GenericFactory()
{
registeredTypes.Add(typeof(int), typeof(GenericInt));
registeredTypes.Add(typeof(string), typeof(GenericString));
}
public static IGeneric<T> CreateGeneric<T>()
{
var t = typeof(T);
if (registeredTypes.ContainsKey(t) == false) throw new NotSupportedException();
var typeToCreate = registeredTypes[t];
return Activator.CreateInstance(typeToCreate, true) as IGeneric<T>;
}
}
public interface IGeneric<TId>
{
TId Id { get; set; }
void ProcessEntity(TId id);
}
public class GenericInt : IGeneric<int>
{
public int Id { get; set; }
public void ProcessEntity(int id)
{
Console.WriteLine(id);
}
}
public class GenericString : IGeneric<string>
{
public string Id { get; set; }
public void ProcessEntity(string id)
{
Console.WriteLine(id);
}
}
The answer marked correct is fine if you want to use Static class but but what if you
want to return an DI injected type instead of newing an object? I suggest the
following!
public interface IGenericFactory
{
IGeneric<T> GetGeneric<T>() where T : class;
}
public class GenericFactory: IGenericFactory
{
private readonly IGeneric<int> intGeneric;
private readonly IGeneric<string> stringGeneric;
public GenericFactory(IGeneric<int> intG, IGeneric<string> stringG)
{
intGeneric = intG;
stringG = stringG;
}
public IGeneric<T> GetGeneric<T>() where T : class
{
if (typeof(T) == typeof(IGeneric<int>))
return (IGeneric<T>)Convert.ChangeType(intGeneric, typeof(IGeneric<T>));
if (typeof(T) == typeof(IGeneric<string>))
return (IGeneric<T>)Convert.ChangeType(stringGeneric,typeof(IGeneric<T>));
else
throw new NotSupportedException();
}
}
Please note i simply injected the two expected return types for clarity in the constructor. I could have implemented the factory as a Dictionary and injected the return objects into this Dictionary. Hope it helps.
I'm thinking you don't want to have to enter the type parameter similar to the LINQ methods. However the magic behind that happens because the type parameter is used in the normal parameter definitions. For example in the ToList<string>() method you can see that TSource is used between the parenthesis.
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source);
That's how the compiler knows that you want a List<string> if you call ToList() instead of ToList<string>() when called from an IEnumerable<string>
However, I don't think you need a generic type parameter in your factory method at all. All you have to do is create a non-generic version of your TGeneric<TId>
public interface IGeneric { }
public interface IGeneric<TId> : IGeneric
{
void ProcessEntity(TId id);
}
And remove the <WhatGoesHere> from the CreateGeneric method:
public static IGeneric CreateGeneric(string recordType)
{
if (recordType == "Client")
{
return new ClientEntity();
}
if (recordType == "Invoice")
{
return new InvoiceEntity();
}
return null;
}
If the function does not know the type, make it generic.
If the children are generics of different types (<int>, <string>), return object and cast inside the same factory class (Factory<T>), It is safe by typeof.
Personally, I prefer to specify the type with generics, without using an additional parameter, eg a string.
public class Program
{
public static void Main(string[] args)
{
List<Number> something = new();
Do(something);
}
public static void Do<T>(List<T> list)
{
list.Add(Factory<T>.Create());
}
}
public abstract class Factory<T>
{
private static Object ConcreteF()
{
if (typeof(T) == typeof(Number))
return new ChildGenericNumber();
throw new Exception("");
}
public static T Create()
{
return (Factory<T>)ConcreteF()).Build();
}
protected abstract T Build();
}
Cant find a simple answer. My problem is I am trying to compare the VALUE of an object in a list to the VALUE of an object...
my class:
public class MatchList
{
public int SomeInt { get; set; }
public decimal SomeDecimal { get; set; }
}
I create theMatchList. It seems that I can only compare the object and not the values for object with 'theMatchList.Contains...'
MatchList ML = new MatchList();
ML.SomeInt = 12;
ML.SomeDecimal = 2.3;
if (theMatchlist.Contains(ML))
{
DoSomething;
}
How do get to fire 'DoSomething'? Assuming that there is an entry in 'theMatchList' where the values equal 12 and 2.3 respectively. I know it has something to do with iequatable, but I dont quite understand how that works. Thanks in advance!
Your naming is a bit unclear, I assume that you actually have a List<MatchList> that you want to find a particular MatchList in (I suggest renaming MatchList to at least MatchItem in that case and preferable something more descriptive).
Then from the documentation of List<T>.Contains:
This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable<T>.Equals method for T (the type of values in the list).
So you will have to implement IEquatable<T> for your class. In addition, the advice is that
[i]f you implement Equals, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method.
If you implement GetHashCode, its result should not change over the lifetime of your object. In most cases, making the class immutable is sufficient. If you need to be able to update the fields, you need to implement GetHashCode differently.
So all in all, if you want to use Contains your class will end up looking something like below:
public class MatchList : IEquatable<MatchList>
{
// Note: Fields are readonly to satisfy GetHashCode contract
private readonly int someInt;
private readonly decimal someDecimal;
// Public constructor creates immutable object
public MatchList(int myInt, decimal myDecimal)
{
this.someInt = myInt;
this.myDecimal = myDecimal;
}
// Properties are now read-only too.
public int SomeInt { get { return this.someInt; } }
public decimal SomeDecimal { get { return this.someDecimal; } }
// Implementation of IEquatable<MatchList>
public bool Equals( MatchList other )
{
return (other != null)
&& (this.SomeInt == other.SomeInt)
&& (this.SomeDecimal == other.SomeDecimal);
}
// Override of Object.Equals
// Calls the IEquatable.Equals version if possible.
public override bool Equals( object obj )
{
return (obj is MatchList) && this.Equals(obj as MatchList);
}
public override int GetHashCode()
{
return (this.someInt * 17) ^ this.someDecimal.GetHashCode();
}
}
As I commented, your question is pretty unclear so I'll do my best to explain the concept.
It's pretty likely what you were trying to code is the items in the list not the list itself:
public class MatchItem : IEquatable<MatchItem>
{
public int SomeInt { get; set; }
public decimal SomeDecimal {get; set; }
public bool Equals(MatchItem item)
{
if(item == null)
return false;
return this.SomeInt == item.SomeInt && this.SomeDecimal == item.SomeDecimal;
}
// You should also override object.ToString, object.Equals & object.GetHashCode.
// Omitted for brevity here!
}
You'll note that has an implementation of IEquatable<MatchItem> which allows it to be compared to other instances of MatchItem.
Thereafter, this code will work:
var items = new List<MatchItem>()
{
new MatchItem{SomeInt = 1, SomeDecimal = 0.3M},
new MatchItem{SomeInt = 12, SomeDecimal = 2.3M}
};
var searchItem = new MatchItem{SomeInt = 1, SomeDecimal = 0.3M};
Console.WriteLine(items.Contains(searchItem)); // true
Working example: http://rextester.com/ZWNC6890
Greetings everyone!
I'll try to make my problem simple: I have an enum to select which ObjType I should use (ObjTypeA and ObjTypeB both inherits from ObjType). So I created a method to extend the given enum, in order to return a new instance according to the selected property in the enum, like follows in the code. I think it works more or less like a factory design pattern. So far so good, but eventually, like in the class MyClass, I may attempt to create n instances of ObjTypeA or ObjTypeB, but I'll have to face the if statement everytime I call the GetObjTypeInstance() method. So:
Can an enum return an instance, something like: public enum EObjType { ObjTypeA = new ObjTypeA(), ObjTypeB = new ObjTypeB() }? Actually, it'd be better to append some GetInstance() method to the ObjTypeA and to the ObjTypeB options in the enum. If there's a way to do this, how can I do it? Doing this I'd avoid those if statements every while step.
Is there any other (and better) way to this this (if you understood my problem...)? How?
Thanks in advance!
Follow the example code:
public static class EObjTypeExt
{
public static ObjType GetObjTypeInstance(this EObjType ot)
{
if (ot == EObjType.ObjTypeA)
{
return new ObjTypeA();
}
else if (ot == EObjType.ObjTypeB)
{
return new ObjTypeB();
}
throw new ArgumentOutOfRangeException("unrecognized type!");
}
}
public enum EObjType { ObjTypeA, ObjTypeB }
public class MyClass
{
ObjType[] obj { get; set; }
public MyClass(EObjType otEnum, int n)
{
this.obj = new ObjType[n];
int i = 0;
while (i < n)
{
this.obj[i] = otEnum.GetObjTypeInstance();
i++;
}
}
}
You'll have to byte this apple somewhere.
Maybe replace the if/elseif chain with switch statement, they work great with enums.
Instead of using an enum, I would use a class that looks like an enum:
public class EObjType {
public static readonly EObjType ObjTypeA = new EObjType(() => (ObjType)(new ObjTypeA));
public static readonly EObjType ObjTypeB = new EObjType(() => (ObjType)(new ObjTypeB));
private readonly Func<ObjType> generator;
private EObjType(Func<ObjType> generator) {
this.generator = generator;
}
public ObjType GetInstanceOfObjType() {
return generator();
}
}
You can then use it exactly as you have been the enum.
EObjType otEnum = EObjType.ObjTypeA;
ObjType obj = otEnum.GetInstanceOfObjType();
You need to use a factory or other creational design pattern.
For instance, you could hold a dictionary from enum key to type value to get the desired class type using selected enum value. Then use reflection to create a new instance (object) of received type.
Initialize static dictionary's values using static constructor of factory class. You can enter the values manually or better yet, load possible values from a config file.
I'm not sure that I'd really advocate this approach, but you could call the enum ToString() method, treat that as your class name and use reflection to instantiate an object of that type.
One advantage of this would be that you could reflect and get the type once, then call the constructor n times in your loop.
As Danny Varod points out, a dictionary mapping your enum values to their Types (or to functions that create those types) would allow you to avoid if statements. Since enum is really just an integer underneath, an array would be more memory and time efficient, but readability is probably most important here.
You could create a factory that allows registration of functions that map to your enumeration, you could that use some sort of registration process to register your different enumerations
public class ObjectFactory
{
private readonly Dictionary<MyObjectType, Func<MyObject>> _store = new Dictionary<MyObjectType, Func<MyObject>>();
public void Register<T>(MyObjectType type) where T: MyObject, new()
{
this.Register(type, () => new T());
}
public void Register(MyObjectType type, Func<MyObject> factory)
{
_store.Add(type, factory);
}
public MyObject CreateInstance(MyObjectType type)
{
Func<MyObject> factory;
if(_store.TryGetValue(type, out factory))
{
return factory.Invoke();
}
return null;
}
}
public enum MyObjectType { A, B }
public class MyObject {}
public class MyObjectA : MyObject {}
public class MyObjectB : MyObject {}
Usage as follows
var factory = new ObjectFactory();
factory.Register<MyObjectA>(MyObjectType.A);
factory.Register<MyObjectB>(MyObjectType.B);
var a = factory.CreateInstance(MyObjectType.A);
var b = factory.CreateInstance(MyObjectType.B);
Assert.IsInstanceOf(typeof(MyObjectA), a);
Assert.IsInstanceOf(typeof(MyObjectB), b);
You could use Activator.CreateInstance.
public class ObjType {}
public class ObjTypeA : ObjType {}
public class ObjTypeB : ObjType {}
public enum EObjType { ObjTypeA, ObjTypeB }
public static class EObjTypeExt
{
public static ObjType GetObjTypeInstance( EObjType ot)
{
object o = Activator.CreateInstance(null,ot.ToString());
return (ObjType)o;
}
}
I'm trying to do this:
public interface IVirtualInterface{ }
public interface IFabricationInfo : IVirtualInterface
{
int Type { get; set; }
int Requirement { get; set; }
}
public interface ICoatingInfo : IVirtualInterface
{
int Type { get; set; }
int Requirement { get; set; }
}
public class FabInfo : IFabricationInfo
{
public int Requirement
{
get { return 1; }
set { }
}
public int Type
{
get {return 1;}
set{}
}
}
public class CoatInfo : ICoatingInfo
{
public int Type
{
get { return 1; }
set { }
}
public int Requirement
{
get { return 1; }
set { }
}
}
public class BusinessObj
{
public T VirtualInterface<T>() where T : IVirtualInterface
{
Type targetInterface = typeof(T);
if (targetInterface.IsAssignableFrom(typeof(IFabricationInfo)))
{
var oFI = new FabInfo();
return (T)oFI;
}
if (targetInterface.IsAssignableFrom(typeof(ICoatingInfo)))
{
var oCI = new CoatInfo();
return (T)oCI;
}
return default(T);
}
}
But getting a compiler error: Canot convert type 'GenericIntf.FabInfo' to T
How do I fix this?
thanks
Sunit
Assuming all IVirtualInterface implementations will have a default constructor (as in your example), you can do this instead:
public T VirtualInterface<T>() where T : IVirtualInterface, new()
{
return new T();
}
Simples!
EDIT:
Exactly what you're trying to achieve is difficult to determine from the code you've posted. Why isn't VirtualInterface static (implies all business objects inherit this method which seems odd)? If you need o be able to parameterised constructors for your IVirtualInterface implementations, where would those parameter values come from (you're not passing any into the VirtualInterface method)?
If you just want to avoid cluttering up intellisense (a poor reason for trying something like this IMHO) but also want to maintain support for parameteried constructors, then how about this:
public T VirtualInterface<T>(Func<T> constructor) where T : IVirtualInterface
{
return constructor();
}
With usage:
IFabricationInfo fabInfo =
new BusinessObj().VirtualInterface<IFabricationInfo>(() => new FabInfo());
Overall though, and without enough information to make a solid judgement, I'd have to say that this smells.
The fact that T and FabInfo both implement IVirtualInterface does not mean you can perform a cast between the two types. For example if T is CoatInfo, then it is not compatible type with FabInfo.
Interfaces allow you to treat different objects as similar types based on the methods they provide. However, this does not mean that you can perform casts between these two types as their actual implementation can vary greatly.
Edit: After re-reading your method again, I see that you are checking the type first. The problem is that the compiler doesn't know you are performing that logic before you try to make that cast. If you are writing a generic method and are checking the type of T, you are likely misusing the concept of generics. See the other answers for the way you should be creating new instances of T.
You can get around this error by first casting to object before casting to T e.g.
return (T)(object)oFI;
and similarly for CoatInfo
However I think switching on a generic type is an abuse, since if you want a limited number of possible return values, you could make the options explicit e.g.
public IFabricationInfo GetFabricationInfo()
{
return new FabInfo();
}