I currently have something like this:
abstract class BaseClass {
public abstract string title();
}
class Derived1 : BaseClass {
public override string title() { return "D1"; }
}
class Derived2 : BaseClass {
public override string title() { return "D2"; }
}
class Receiver<T> where T : BaseClass {
private T obj;
public string objTitle() { return obj.title(); }
}
The problem I am running into is that, if obj is null, objTitle throws a null reference exception. I can guarentee in this case that title will always return the same string for a given derived type; is there any way to make Receiver able to access it on the generic parameter T? My instinct is to use a static, but I don't know of any way to make a static visible to the Reciever; there's no way to make a base class or constraint specifying it.
You could use reflection to call a static method on the type, or if the value is actually a constant, you could also instantiate a new instance if there isn't an instance yet.
class Receiver<T> where T : BaseClass, new() {
private T obj;
public string objTitle() { return (obj ?? new T()).title(); }
}
What I would do is construct the T immediately and drop the if
class Receiver<T> where T : BaseClass, new() {
private T obj = new T();
public string objTitle() { return obj.title(); }
}
In C# you can't override static methods. From your design I can see that "title" is independent with an instance of BaseClass/Derived1/Derived2. Adding an instance method title() doesn't make sense here. I recommend you design these classes like this: (I renamed the classes to make it easy to understand)
abstract class MessageBase { }
class TextMessage : MessageBase { }
class ImageMessage : MessageBase { }
class Receiver<T> where T : MessageBase
{
public string GetMessageTitle()
{
if (typeof(T) == typeof(TextMessage)) return "Text";
else if (typeof(T) == typeof(ImageMessage)) return "Image";
return "Default";
}
}
Related
I have a base abstract class which is meant to allow implementors to return different types:
protected abstract T GetMyValue<T>();
I would like the implementing class to be able to do something like this:
T myResult;
public override T GetMyValue<T>()
{
return _myResult;
}
I would like the caller to specify the type:
int i = obj.GetMyValue<int>();
Is this possible?
Like an object extension?
public static class ObjectExtension
{
public static T GetValue<T>(this object obj)
{
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter == null)
return default(T);
return (T)converter.ConvertFrom(obj);
}
}
One option would just be to store the field as an object. This will cause boxing for structs, but there isn't better way without a more significant change.
class Derived : Base
{
private object o;
protected override T GetMyValue<T>()
{
if (o is T)
return (T)o;
return default(T);
}
}
You can't really have a generic field unless the abstract class is itself generic, not the specific method. Of course this is a significant design change. One implementation can now only return one type. Something like
abstract class BaseClass<T>
{
protected abstract T GetMyValue();
}
class Derived : Base<int>
{
private int i;
protected override int GetMyValue()
{
return i;
}
}
You somehow have to make the field have the same type that you want to return. Here's a trick for that:
public override T GetMyValue<T>()
{
return ValueHolder<T>.GetMyValue();
}
class ValueHolder<T> {
static T myResult;
public static T GetMyValue()
{
return myResult;
}
}
Because this is a static class there can only be one such value.
If you want to have one value per type in your instance you need a Dictionary<Type, object>.
I have a base class that has a property and a method that uses that property. I have a class that inherits that base class and has its own implementation of the base class's property that is explicitly hidden using the New modifier. In the base class' method, is there a good way to use the inherited class' property instead of the base's implementation?
class Program
{
public class MyBase
{
public string MyProperty { get { return "Base"; } }
public string MyBaseMethod()
{
return MyProperty;
}
}
public class MyInherited : MyBase
{
public new string MyProperty { get { return "Inherited"; } }
}
static void Main(string[] args)
{
List<MyBase> test = new List<MyBase>();
test.Add(new MyBase());
test.Add(new MyInherited());
foreach (MyBase item in test)
{
Console.WriteLine(item.MyBaseMethod());
}
}
}
In the example, the output is:
Base
Base
Current workaround:
...
public class MyBase
{
public string MyProperty { get { return "Base"; } }
public string MyBaseMethod()
{
if (this is MyInherited)
{
return baseMethod(((MyInherited)this).MyProperty);
}
else
{
return baseMethod(MyProperty);
}
}
private string baseMethod(string input)
{
return input;
}
}
...
Is there a better way to do this? I'd rather not have to do explicit type casts.
Hiding a member with the new keyword should generally be avoided. Instead make the base class' property virtual and override it in the descending class. The MyBaseMethod will automatically use this overridden property in inheriting classes.
public class MyBase
{
public virtual string MyProperty { get { return "Base"; } }
public string MyBaseMethod()
{
return MyProperty;
}
}
public class MyInherited : MyBase
{
public override string MyProperty { get { return "Inherited"; } }
}
var inherited = new MyInherited();
Console.WriteLine(inherited.MyBaseMethod()); // ==> "Inherited"
See this interesting post related to the new keyword: Why do we need the new keyword and why is the default behavior to hide and not override?
Make the property virtual, not sealed, and override it, rather than shadowing it. Then all uses of the property will use the most derived implementation of it.
There is no such way. If you do new (which is early binding), you have to do explicit casts. The only solution is to make the property virtual. Then you can override it (using the override modifier). This is late binding.
Here is the code.
public class EData {
public static EData All(){
return null;
}
}
public class EHouse : EData {
}
I don't want the function All in class EHouse return EData but return EHouse.
EHouse.All() should return a type of EHouse without coding anything extra in derived classes.
Well, you can use Self Referencing Generics but those can sometimes cause issues. But you get something like this:
public class EData<T> where T : EData<T>
{
public static T All(){
return null;
}
}
public class EHouse : EData<EHouse>
{
}
With usage like:
EHouse all = EHouse.All();
But not sure if this violates your constraint of "not having to code anything in your derived class" as it changes its inheritance declaration slightly.
You could try EData having generic type parameters:
public class EData<T>
{
public static T All()
{ return (T) ..... }
}
public class EHouse : EData<EHouse> { }
I often use the class-factory pattern whereby a class has a private constructor and a static method to create the class. This allows for the situation where the class cannot be constructed for some reason, and a null is returned - very handy.
I would like to be able to extend this to a factory method which creates a particular class from a hierarchy of derived classes depending on conditions. However I can't see a way of then hiding the constructors of the derived classes to force the use of the factory method. If the factory method is in the base class it no longer has access to the private constructors of derived classes. Putting a factory method in every derived class doesn't work as the required type must then be known beforehand. Nested classes might be a way if a class had access to the private members of a nested class, but sadly it seems that the nested classes have access to the private members of the enclosing class, but not the other way round.
Does anyone know of a way of doing this?
There are several possibilities, two of which are:
Put all those classes in one project and make the constructors internal. Other projects won't be able to call those constructors but the code inside that project can.
Make the constructors of those classes protected (instead of private) and create a private derived class in the class containing the factory method. Create an instance of that private class and return it.
Example for the second option:
public static class AnimalFactory
{
public static Animal Create(int parameter)
{
switch(parameter)
{
case 0:
return new DogProxy();
case 1:
return new CatProxy();
default:
throw new ArgumentOutOfRangeException("parameter");
}
}
private class DogProxy : Dog { }
private class CatProxy : Cat { }
}
public abstract class Animal { }
public class Dog : Animal
{
protected Dog() { }
}
public class Cat : Animal
{
protected Cat() { }
}
Here's the sample code I was working on when Daniel posted his answer. It looks like it's doing what he suggested:
public static class BaseFactory
{
public static Base Create(bool condition)
{
if (condition)
{
return Derived1.Create(1, "TEST");
}
else
{
return Derived2.Create(1, DateTime.Now);
}
}
}
public class Base
{
protected Base(int value)
{
}
protected static Base Create(int value)
{
return new Base(value);
}
}
public sealed class Derived1: Base
{
private Derived1(int value, string text): base(value)
{
}
internal static Derived1 Create(int value, string text)
{
return new Derived1(value, text);
}
}
public sealed class Derived2: Base
{
private Derived2(int value, DateTime time): base(value)
{
}
internal static Derived2 Create(int value, DateTime time)
{
return new Derived2(value, time);
}
}
[EDIT] And for Daniel's second suggestion:
public static class BaseFactory
{
public static Base Create(bool condition)
{
if (condition)
{
return new Derived1Creator(1, "TEST");
}
else
{
return new Derived2Creator(1, DateTime.Now);
}
}
private sealed class Derived1Creator: Derived1
{
public Derived1Creator(int value, string text): base(value, text)
{
}
}
private sealed class Derived2Creator: Derived2
{
public Derived2Creator(int value, DateTime time): base(value, time)
{
}
}
}
public class Base
{
protected Base(int value)
{
}
protected static Base Create(int value)
{
return new Base(value);
}
}
public class Derived1: Base
{
protected Derived1(int value, string text): base(value)
{
}
protected static Derived1 Create(int value, string text)
{
return new Derived1(value, text);
}
}
public class Derived2: Base
{
protected Derived2(int value, DateTime time): base(value)
{
}
protected static Derived2 Create(int value, DateTime time)
{
return new Derived2(value, time);
}
}
Note that this second approach means that the classes can't be sealed, unfortunately.
Rather than using methods inside the class itself as a factory implement the Factory pattern by means of a static class ("the factory") that returns the correct instance based on the logic you write.
You can intercept the derived type creation in the base class contructor and check that the caller is your factory using StackFrames:
protected Class1() //base class ctor
{
StackFrame[] stackFrames = new StackTrace().GetFrames();
foreach (var frame in stackFrames)
{
//check caller and throw an exception if not satisfied
}
}
Please look at the code bellow:
public class BaseClass
{
}
public class SubClass : BaseClass
{
}
public class QueryClass
{
public TBaseClass[] QueryBase<TBaseClass>() where TBaseClass : BaseClass
{
throw new NotImplementedException();
}
public TSubClass[] QuerySub<TSubClass>() where TSubClass : SubClass
{
throw new NotImplementedException();
}
public TClass[] Query<TClass>() where TClass : BaseClass
{
if (typeof(TClass).IsSubclassOf(typeof(SubClass)))
{
return QuerySub<TClass>(); // there is error The type 'TClass' must be convertible to SubClass
}
return QueryBase<TClass>();
}
}
The question is how to implement Query method. If it is possible..
What you are trying to do is doing something like this:
public class Animal { }
public class Dog : Animal { }
public void HandleAnimal<T>() where T : Animal
{
}
public void HandleDog<T>() where T : Dog
{
}
When you have a reference to Animal in this case, there is no way of knowing what typeof animal it is. Even if the method returns true, in the context of your code it is still always an Animal and you can't handle a dog when all you know is that the type is an animal. If you were handling instances of objects inside the method you could potentially start casting or instansiating the subclass if you know that it is a subclass and then pass that through.
Ended up with reflection.
if (typeof(TClass).IsSubclassOf(typeof(SubClass)))
{
var method = typeof(QueryClass).GetMethod("QuerySub").MakeGenericMethod(typeof (TClass));
return (TClass[]) method.Invoke(this, new object[0]);
}