public class Foo
{
public const int type = 1;
}
Why can't i do this? Is there a reason behind it or am I trying to access the constant in a wrong way?
new Foo().type;
I know I can do Foo.type but given my scenario, I cant do that. For example if I have two class which inherit from a base class like this:
public class Base
{
...
}
public class Foo : Base
{
public const int type = 0;
}
public class Bar : Base
{
public const int type = 1;
}
public static void printType(Base b)
{
Console.WriteLine(b.type);
}
I would want to get the type property of the class sent through the printType() function but I cant since I can only access the type from the Class, not the object its self.
A work around would be to do
if(b is Foo){
Console.Write(Foo.type);
}elseif....
but this seems stupid and not viable if you have many sub classes of Base
Solution
I ended up using readonly instead of const like this:
public readonly int type = 0;
Yes, you're trying to access it in the wrong way. A constant isn't associated with an instance of a type - it's associated with the type itself. So you want:
int x = Foo.type;
Basically, const members are implicitly static, and C# doesn't let you access static members as if they were instance members, via a value. (Note that in .NET naming conventions, it should be Type rather than type.)
EDIT: Now that you've explained the actual situation, it appears you're trying to use polymorphism, which won't work for constants. So instead, you should have an abstract property in the base class, implemented in subclasses.
public abstract class Base
{
public abstract int Type { get; }
}
public class Foo : Base
{
public override int Type { get { return 0; } }
}
public class Bar : Base
{
public override int Type { get { return 0; } }
}
Alternatively, just have a normal property in the base class which is populated via the base class constructor:
public class Base
{
private readonly int type;
public int Type { get { return type; } }
protected Base(int type)
{
this.type = type;
}
}
public class Foo : Base
{
public Foo() : base(0) {}
}
public class Bar : Base
{
public Bar() : base(1) {}
}
If you just want something to identify the dynamic (most-derived) type of the object passed in, that's built into .NET, via the Object.GetType() method.
public static void printType(Base b)
{
Console.WriteLine(b.GetType().Name);
}
Of course, this isn't quite the same as having attached data under your control. You can, however, use a Dictionary<Type, T> to associate data of arbitrary type with the various subclasses. It would be reasonable to use the subclass type initializer to install new entries into such a dictionary.
public class Base
{
static internal readonly Dictionary<System.Type, int> TypeMap =
new Dictionary<System.Type, int>();
}
public class Foo : Base
{
static Foo { TypeMap.Add(typeof(Foo), 0); }
}
public class Bar : Base
{
static Bar { TypeMap.Add(typeof(Bar), 1); }
}
public static void printType(Base b)
{
Console.WriteLine(Base.TypeMap[b.GetType()]);
}
This WILL be a bit slower than the field-per-object method, however it doesn't add any extra storage per-object.
Related
I have a simple class, which looks something like this:
public class MyClass<T>
{
public int Status { get; set; }
public T Value { get; set; }
}
For convenience, I have another class which inherits from MyClass<string>, to allow me to construct MyClass without generic arguments, such as:
public class MyClass : MyClass<string> { }
I want to be able to cast MyClass<T> to MyClass, and it seems this doesnt work by default. This example cast throws the following error:
MyClass<string> withT = new MyClass<string> { Status = 1, Value = "Somevalue" };
MyClass withoutT = (MyClass)withT;
Unable to cast object of type 'MyClass`1[System.String]' to 'MyClass'
So I believe I need to implement some implicit/explicit casting logic, as described in this answer.
I've updated MyClass<T> as follows, however the same error is still thrown:
public class MyClass<T>
{
public int Status { get; set; }
public T Value;
public static implicit operator MyClass(MyClass<T> myClass)
{
return new MyClass
{
Status = myClass.Status,
Value = myClass.Value.GetType() == typeof(string) ? myClass.Value.ToString() : null
};
}
}
Can anyone help point out where I'm going wrong?
Why not use a factory? Here's a very simple example:
public static class MyClass
{
public static MyClass<string> Create(string s, int status)
{
return new MyClass<string>(s, status);
}
}
...
var x = MyClass.Create("Foo", 0);
Consider making MyClass<T> a must inherit class (with the abstract keyword) so it cannot be instantiated. This way you can only create objects from derived classes, which you can down cast to the base class.
Also if you want a type reference to the derived types (for casting) then include that in the type parameters. Add a TDerived which much inherit from MyClass<T> as such:
public abstract class MyClass<TDerived, TValue> where TDerived : MyClass<TDerived, TValue>
{
protected MyClass(int status, TValue value)
{
this.Status = status;
this.Value = value;
}
public int Status { get; set; }
public TValue Value { get; set; }
public static implicit operator TDerived(MyClass<TDerived, TValue> myClass)
=> myClass as TDerived;
}
public class SpecificClass : MyClass<SpecificClass, string>
{
public SpecificClass(int status, string value) : base(status, value)
{
// The ONLY way to instantiate a MyClass<> is from a derived class
// such as this.
}
}
class Program
{
static void Main(string[] args)
{
MyClass<SpecificClass, string> my_class = new SpecificClass(-1, "ABC");
SpecificClass my_specific = my_class;
}
}
Jon Skeet is right in his comments.
Throw out generics altogether. Can you do this?
class X {}
class Y : X {}
...
var x = new X();
var y = (Y)x;
No. You cannot. An X is not a Y. Similarly a MyClass<string> is not a MyClass.
Taking it further your casting code still doesn't work as you've stated, and trying to define an implicit or explicit cast operator in other ways (e.g. typed specifically with string) won't even compile.
Solutions
Do l33t's solution. It's the most straight forward.
Do #ja72's solution. It works and is the most generic.
Create your own static methods that do conversion or create extension methods that do the conversion.
Break the inheritance of MyClass from MyClass<string> and define your operators. Yes, that means some redundant code.
Why can't we call the constructor of the base class within the function body of the constructor of a subclass? For example,
public class Baseclass
{
public int X;
public Baseclass () { }
public Baseclass (int x) { this.X = x; }
}
why
public class Subclass : Baseclass
{
public Subclass (int x) : base (x) { }
}
instead of
public class Subclass : Baseclass
{
public Subclass (int x) : { base(x); }
}
or
public class Subclass : Baseclass
{
public Subclass (int x) : { base.Baseclass(x); }
}
My question is more from the perspective of the design of C#, or other similar OO languages such as C++ and Java, which all follow the same design.
Thanks.
Java does not actually allow what you're proposing - while in Java the call to super() is inside the subclass constructor's body it is a compile error if there are any statements before that call:
// This is Java
public class Subclass extends ParentClass {
public Subclass() {
String x = "foo";
super(); // <-- compile error
}
}
Anyway, the reason is because the runtime (and language specification) demands that the state of a superclass be fully-defined prior to any subclass instance code being executed.
A simple thought-experiment will demonstrate why:
// This is C#
public class ParentClass {
protected readonly Int32 x;
public ParentClass() {
this.x = 123;
}
}
public class Subclass : ParentClass {
// Using your proposed idea:
public Subclass() {
Int32 localX = base.x; // get the current value of `ParentClass.x`
base(); // call base constructor
}
}
In the example above, what is the value of localX?
The answer is "undefined" - and C# and the CLR (and Java) are designed to prevent undefined behaviour - whereas C++ is more forgiving, but that doesn't mean you should do it.
By requiring that all base classes are fully initialized before subclasses prevents an entire series of bugs relating to uninitialized data.
I will say one thing, however - there is no formal reason why we should not be able to execute static code prior to calling the parent constructor. We can actually do this in C# but we have to refactor code so it's a static function call via the parent class' constructor parameters, which isn't pretty - nor does it allow data to be passed directly back to the subclass constructor. So I wish we could do something like this:
public class ParentClass {
public ParentClass(String x, Int32 y) {
// ...
}
}
public class Subclass : ParentClass {
private static ComplexObject GetComplexObject() {
// ...
}
public Subclass() {
// All code before `base()` is executed in a static context:
ComplexObject cmplx = GetComplexObject();
base( cmplx.X, cmplx.Y );
}
}
Instead we currently need to do this:
public Subclass()
: base( GetComplexObject().X, GetComplexObject().Y ) {
}
Or use a static factory method with a private constructor:
private Subclass(String x, Int32 y) : base( x, y ) {
}
public static Subclass Create() {
ComplexObject cmplx = GetComplexObject();
return new Subclass( cmplx.X, cmplx.Y );
}
public class Subclass : Baseclass
{
public Subclass (int x) : base (x) { }
}
Yes this one is the correct answer. I've tried java but the syntax of almost c# codes are different. As soon as you call the base class with constructor on your subclass you need to follow the way you code it from the base class;
You may also try this upon instantiating
Baseclass base = new Baseclass(32);
I have an interface for a base class, and every class that inherits from the base class should have an identifying field which tells the application what kind of object it is.
I wanted to use this property in two different ways:
Without creating an instance of the object
if (someValue == TestA.Id)
return new TestA();
elseif (someValue == TestB.Id)
return new TestB();
And as a property of the interface
void DoSomething(ITest testObject)
{
SomeValue = testObject.Id;
}
Is there an easy way to define the Id field in the interface, but still have it available to use without creating an instance of the class?
Right now I am using the following code. I could add a read-only Id property to the interface which returns the const string, however I was hoping there was a simpler way that I'm just not aware of.
public interface ITest
{
}
public class TestA : ITest
{
public const string Id = "A";
}
In short - no.
In order to be able to do this, you'd need to be able to specify this as a instance property on the interface (and implement it in the instance), and as a static property on the type.
The compiler won't let you do this.
You can put it in the interface, and also have it as a static property. Something like:
interface IInterface { Id { get; } }
class Class : IInterface
{
public static Id { get { return 1; } }
public Id { get { return Class.Id; } }
}
I've faced a similar problem, Rachel, and I've always (unfortunately) resorted to having that factory code rely on reflection to get a "TypeID" public static property on each concrete type... thus making an additional aspect of the contractual interface, but not having it in the C# interface code.
You could do it this way.
public interface ITest
{
SomeValue Id{ get;}
}
public class TestA : ITest
{
public SomeValue Id
{
get {return TestA.StaicId; }
}
public static SomeValue StaticId
{
get {return "This is TestA";}
}
}
if (someValue == TestA.StaticId)
return new TestA();
How about using attributes? Here's a small example of what can be done:
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class IdAttribute : Attribute
{
public IdAttribute(string id)
{
this.Id = id;
}
public string Id { get; set; }
}
public interface IMyInterface
{
}
public abstract class BaseClass : IMyInterface
{
public static string GetId<T>() where T : IMyInterface
{
return ((IdAttribute)typeof(T).GetCustomAttributes(typeof(IdAttribute), true)[0]).Id;
}
}
[Id("A")]
public class ImplA : BaseClass
{
}
[Id("B")]
public class ImplB : BaseClass
{
}
internal class Program
{
private static void Main(string[] args)
{
var val1 = BaseClass.GetId<ImplA>();
var val2 = BaseClass.GetId<ImplB>();
Console.ReadKey();
}
}
I am trying to accomplish the following scenario that the generic TestClassWrapper will be able to access static properties of classes it is made of (they will all derive from TestClass). Something like:
public class TestClass
{
public static int x = 5;
}
public class TestClassWrapper<T> where T : TestClass
{
public int test()
{
return T.x;
}
}
Gives the error:
'T' is a 'type parameter', which is not valid in the given context.
Any suggestions?
You can't, basically, at least not without reflection.
One option is to put a delegate in your constructor so that whoever creates an instance can specify how to get at it:
var wrapper = new TestClassWrapper<TestClass>(() => TestClass.x);
You could do it with reflection if necessary:
public class TestClassWrapper<T> where T : TestClass
{
private static readonly FieldInfo field = typeof(T).GetField("x");
public int test()
{
return (int) field.GetValue(null);
}
}
(Add appropriate binding flags if necessary.)
This isn't great, but at least you only need to look up the field once...
Surely you can just write this:
public int test()
{
return TestClass.x;
}
Even in a nontrivial example, you can't override a static field so will always call it from your known base class.
Why not just return TestClass.x?
Generics do not support anything related to static members, so that won't work. My advice would be: don't make it static. Assuming the field genuinely relates to the specific T, you could also use reflection:
return (int) typeof(T).GetField("x").GetValue(null);
but I don't recommend it.
Another solution is to simply not make it static, and work with the new() constraint on T to instantiate the object. Then you can work with an interface, and the wrapper can get the property out of any class that implements that interface:
public interface XExposer
{
Int32 X { get; }
}
public class TestClass : XExposer
{
public Int32 X { get { return 5;} }
}
public class XExposerWrapper<T> where T : XExposer, new()
{
public Int32 X
{
get { return new T().X; }
}
}
In fact, you can change that to public static Int32 X on the TestClassWrapper and simply get it out as Int32 fetchedX = XExposerWrapper<TestClass>.X;
Though since whatever code calls this will have to give the parameter T those same constraints, the wrapper class is pretty unnecessary at this point, since that calling code itself could also just execute new T().X and not bother with the wrapper.
Still, there are some interesting inheritance models where this kind of structure is useful. For example, an abstract class SuperClass<T> where T : SuperClass<T>, new() can both instantiate and return type T in its static functions, effectively allowing you to make inheritable static functions that adapt to the child classes (which would then need to be defined as class ChildClass : SuperClass<ChildClass>). By defining protected abstract functions / properties on the superclass, you can make functions that apply the same logic on any inherited object, but customized to that subclass according to its implementations of these abstracts. I use this for database classes where the table name and fetch query are implemented by the child class. Since the properties are protected, they are never exposed, either.
For example, on database classes, where the actual fetching logic is put in one central abstract class:
public abstract class DbClass<T> where T : DbClass<T>, new()
{
protected abstract String FetchQuery { get; }
protected abstract void Initialize(DatabaseRecord row);
public static T FetchObject(DatabaseSession dbSession, Int32 key)
{
T obj = new T();
DatabaseRecord record = dbSession.RetrieveRecord(obj.FetchQuery, key);
obj.Initialize(record);
return obj;
}
}
And the implementation:
public class User : DbClass<User>
{
public Int32 Key { get; private set;}
public String FirstName { get; set;}
public String LastName { get; set;}
protected override String FetchQuery
{ get { return "SELECT * FROM USER WHERE KEY = {0}";} }
protected override void Initialize(DatabaseRecord row)
{
this.Key = DbTools.SafeGetInt(row.GetField("KEY"));
this.FirstName = DbTools.SafeGetString(row.GetField("FIRST_NAME"));
this.LastName = DbTools.SafeGetString(row.GetField("LAST_NAME"));
}
}
This can be used as:
User usr = User.FetchObject(dbSession, userKey);
This is a rather simplified example, but as you see, this system allows a static function from the parent class to be called on the child class, to return an object of the child class.
T is a type, not parameter or variable so you cannot pick any value from any members. Here is a sample code.
public class UrlRecordService
{
public virtual void SaveSlug<T>(T entity) where T : ISlugSupport
{
if (entity == null)
throw new ArgumentNullException("entity");
int entityId = entity.Id;
string entityName = typeof(T).Name;
}
}
public interface ISlugSupport
{
int Id { get; set; }
}
cjk and Haris Hasan have the most-correct answers to the question as asked. However in this comment the OP implies that he is after something else not quite possible in C#: a way to define a contract for a static member in a derived class.
There isn't a way to strictly define this, but it is possible to set up a pattern that may be implied by a base class (or interface); e.g.:
public class TestClass
{
private static int x;
public virtual int StaticX => x;
}
or if not intended to be used directly
public abstract class AbstractTestClass
{
public abstract int StaticX {get;}
}
or (my preference in this contrived example)
public interface ITest
{
int StaticX {get;}
}
Elsewhere, this pattern of a StaticXxx member may be (loosely) associated with implementations that should back the member with static fields (as in TestClass above).
What's kind of fun is that this can be (re)exposed as static by the generic wrapper, because generic statics are isolated to each type used.
public class TestClassWrapper<T> where T : ITest, new()
{
private readonly static T testInstance = new T();
public static int test() => testInstance.x;
}
This uses a new() condition, but an associated static, generic factory pattern for creating ITest (or TestClass or AbstractTestClass) instances may also be used.
However this may not be feasible if you can't have long-lived instances of the class.
In this situation you assume that T is a subclass of TestClass. Subclasses of TestClass will not have the static int x.
I want to force subclasses to define a constant value.
Like
const string SomeConstantEverySubclassMustDefine = "abc";
I need that because I need to have it tied to the Type, rather than to the instance and you can't override static Methods/Properties iirc.
I'd really like to have a compile-time check for those constants.
Let me explain in more detail:
Some classes in our Domain-Model are special, you can take certain actions for them, depending on the type. Thus the logic is tied to the type. The action to be taken requires a string tied to the type. I sure could create an instance everytime as a workaround and declare an abstract property, but that's not what I want. I want to enforce the declaration of the string at compile-time, just to be sure.
No, you can't. I would suggest you make your base class abstract, with an abstract property which you can fetch when you want. Each child class can then implement the property just by returning a constant if it wants. The downside is that you can't use this within static methods in the base class - but those aren't associated with the child classes anyway.
(It also allows child classes to customise the property per instance as well, if necessary... but that's rarely an actual problem.)
If this doesn't do enough for you, you might want to consider a parallel type hierarchy. Basically polymorphism simply doesn't happen in a type-specific way in .NET; only in an instance-specific way.
If you still want to do this and fetch it with reflection, I suggest you just write unit tests to ensure that the relevant constants are defined. When you get beyond what the type system can describe, that's often the best you can do.
Make an abstract property with only a get. That's what I think you could do to enforce a class has a value. Then you can just return a constant in the property.
Example:
Base class:
public abstract string MyConst { get; }
Derived class:
public override string MyConst {
get { return "constant"; }
}
Here is how I made mine work. I used Attribute as others have suggested.
public class ObjectAttribute : Attribute
{
public int ObjectSize { get; set; }
public ObjectAttribute(int objectSize)
{
this.ObjectSize = objectSize;
}
}
public abstract class BaseObject
{
public static int GetObjectSize<T>() where T : IPacket
{
ObjectAttribute[] attributes = (ObjectAttribute[])typeof(T).GetCustomAttributes(typeof(ObjectAttribute), false);
return attributes.Length > 0 ? attributes[0].ObjectSize : 0;
}
}
[ObjectAttribute(15)]
public class AObject : BaseObject
{
public string Code { get; set; }
public int Height { get; set; }
}
[ObjectAttribute(25)]
public class BObject : BaseObject
{
public string Code { get; set; }
public int Weight { get; set; }
}
If you would like instance access to the attribute just add it to the base abstract class.
public abstract class BaseObject
{
public static int GetObjectSize<T>() where T : IPacket
{
ObjectAttribute[] attributes = (ObjectAttribute[])typeof(T).GetCustomAttributes(typeof(ObjectAttribute), false);
return attributes.Length > 0 ? attributes[0].ObjectSize : 0;
}
public int ObjectSize
{
get
{
ObjectAttribute[] attributes = (ObjectAttribute[])GetType().GetCustomAttributes(typeof(ObjectAttribute), false);
return attributes.Length > 0 ? attributes[0].ObjectSize : 0;
}
}
}
Usage of the constants
int constantValueA = AObject.GetObjectSize<AObject>();
int constantValueB = BObject.GetObjectSize<BObject>();
AObject aInstance = new AObject();
int instanceValueA = aInstance.ObjectSize;
New idea
Here's a sort of weird idea: instead of using inheritance directly, you create a separate class to provide a constant value for every type deriving from some type T. The constructor for this type uses reflection to verify that every derived type has indeed been supplied a value.
public abstract class Constant<T, TConstant>
{
private Dictionary<Type, TConstant> _constants;
protected Constant()
{
_constants = new Dictionary<Type, TConstant>();
// Here any class deriving from Constant<T, TConstant>
// should put a value in the dictionary for every type
// deriving from T, using the DefineConstant method below.
DefineConstants();
EnsureConstantsDefinedForAllTypes();
}
protected abstract void DefineConstants();
protected void DefineConstant<U>(TConstant constant) where U : T
{
_constants[typeof(U)] = constant;
}
private void EnsureConstantsDefinedForAllTypes()
{
Type baseType = typeof(T);
// Here we discover all types deriving from T
// and verify that each has a key present in the
// dictionary.
var appDomain = AppDomain.CurrentDomain;
var assemblies = appDomain.GetAssemblies();
var types = assemblies
.SelectMany(a => a.GetTypes())
.Where(t => baseType.IsAssignableFrom(t));
foreach (Type t in types)
{
if (!_constants.ContainsKey(t))
{
throw new Exception(
string.Format("No constant defined for type '{0}'.", t)
);
}
}
}
public TConstant GetValue<U>() where U : T
{
return _constants[typeof(U)];
}
}
Basic example:
public class BaseType
{
public static Constant<BaseType, string> Description { get; private set; }
static BaseType()
{
Description = new BaseTypeDescription();
}
}
public class DerivedType : BaseType
{ }
internal sealed class BaseTypeDescription : Constant<BaseType, string>
{
public BaseTypeDescription() : base()
{ }
protected override DefineConstants()
{
DefineConstant<BaseType>("A base type");
DefineConstant<DerivedType>("A derived type");
}
}
Now I have code that allows me to do this:
var description = BaseType.Description;
// returns "A base type"
string baseTypeDescription = description.GetValue<BaseType>();
// returns "A derived type"
string derivedTypeDescription = description.GetValue<DerivedType>();
Original answer
You may not like it, but the closest way to accomplish this is by declaring an abstract read-only (no set) property.
If you've got an instance of your subclass, then this can work just as well as a constant, even though it is technically instance-level (it will just be the same for all instances of the given class).
Consider, for instance, IList.IsReadOnly. In most cases this is actually a property that tells you about the underlying class implementation, as opposed to any state specific to a particular instance. (It may be an interface member as opposed to an abstract class member, but it's the same idea.)
If you are trying to access it statically, well... then you're out of luck. But in this case I fail to see how you'd obtain the value without using reflection anyway. Maybe that's your intention; I don't know.
You could have a static method in the base class called, for instance "Register", that is passed a Type and a constant value, with the intention being that it is called by the class constructors of the subtypes. Then, add a check in all of your base class constructors that the object being constructed is of a registered type.
abstract class Base
{
private static Dictionary<Type, string> _registry = new Dictionary<Type, string>();
protected static void Register(Type t, string constVal)
{
_registry.Add(t, constVal);
}
protected Base()
{
if(!_registry.ContainsKey(this.GetType()))
throw new NotSupportedException("Type must have a registered constant");
}
public string TypeConstant
{
get
{
return _registry[this.GetType()];
}
}
}
class GoodSubtype : Base
{
static GoodSubtype()
{
Base.Register(typeof(GoodSubtype), "Good");
}
public GoodSubtype()
: base()
{
}
}
class Badsubtype : Base
{
public Badsubtype()
: base()
{
}
}
And then elsewhere, you can construct GoodSubtype instances, but trying to construct a Badsubtype gets an exception. I think a runtime error at construction is the soonest you can get an error with this type of scheme.
(You'd want to use ConcurrentDictionary for your registry if threading is involved)
There's one other method that hasn't been covered and it uses the new modifier to hide consts values in the base class. In a way, it's similar to Nap's solution, but doesn't allow per-instance access and therefore doesn't allow for polymorphic access within the base class. This solution is only useful if you want to have constant value defined but wish to have the option of changing it to different values in different subclasses.
static void Main(string[] args)
{
Console.WriteLine("BaseClass.MyConst = {0}, ClassA.MyConst = {1}, ClassB.MyConst = {2}", BaseClass.MyConst, ClassA.MyConst, ClassB.MyConst);
Console.ReadKey();
}
class BaseClass
{
public const int MyConst = 1;
}
class ClassA : BaseClass
{
public new const int MyConst = 2;
}
class ClassB : BaseClass
{
}