I was just coding a simple C# interface, and I put a property in it without thinking it through too far. For example:
public interface IMyInterface
{
string Name { get; set; }
object[][] Data { get; set;
}
I realized that I'm a little confused with properties when applied to interfaces and abstract base classes. In a normal class, this syntax would generate the accessor and mutator for a hidden string member that it generated behind the scenes.
Interfaces shouldn't be able to have data members. So, does this syntax do something different in that case?
What about for abstract classes? If I put this same syntax in the abstract base and the derived class, would both end up with a hidden member?
Interfaces shouldn't be able to have data members.
Those are properties, and those are allowed:
An interface contains only the signatures of methods, properties, events or indexers.
See also c# properties on Interface.
As for your second question:
If I put this same syntax in the abstract base and the derived class, would both end up with a hidden member?
Yes. You can prevent that by marking the property virtual on the base class and override on the derived class.
The property declaration in the interface is completely separate from the implementation. Thus you can implement it using automatic properties
private class MyImpl : IMyInterface
{
public string Name { get; set; }
public object[][] Data { get; set; }
}
or declare your own backing field
private class MyImplBacked : IMyInterface
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public object[][] Data { get; set; }
}
Same scenario in abstract classes
public abstract class MyAbstractClass
{
public abstract string Name { get; set; }
public abstract object[][] Data { get; set; }
}
private class MyImpl : MyAbstractClass
{
public override string Name { get; set; }
public override object[][] Data { get; set; }
}
private class MyImplBacked : MyAbstractClass
{
private string _name;
public override string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public override object[][] Data { get; set; }
}
Interfaces shouldn't be able to have data members. So, does this syntax do something different in that case?
Technically it's not a data member - it's a get/set method pair that has an underlying data member. There's no implementation.
What about for abstract classes? If I put this same syntax in the abstract base and the derived class, would both end up with a hidden member?
If the class is abstract and the property is virtual then yes, you will be overriding an auto-implemented property with another auto-implemented property (which is pointless).
If the class is abstract and the property is NOT virtual then you still have two implementations, but the base class is hiding the parent implementation rather than overriding it (which is still pointless if they're both auto-implemented).
If the property is abstract then the abstract class won't have an implementation. You'll have to implement the get/set in your concrete class (which could be auto-implemented bot doesn't have to be).
Related
I have an Interface for a master-detail common interface hierarchy:
public interface ITModel
{
ITPeriodHead[] PeriodHeads { get; set; }
}
I try to use it this way:
public class T19Model:ITModel
{
public T19Item[] Items { get; set; }
**public T19PeriodHead[] PeriodHeads { get; set; }**
}
The array of PeriodHeads causes error at compile time,
despite T19PeriodHead implements ITPeriodHead, like this:
public class T19PeriodHead : BaseTPeriodHead, ITPeriodHead
{ ...
What is the solution? If I use the array of ITPeriodHead, I will not be able to access the periodhead items members, properties, methods....
Any help is appriciated.
You have to honor the interface contract. You are returning a more specific class that the interface defines, so you are not fully defining the interface.
You could explicitly implement the interface, but you have an issue with the setter - what if someone tries to set the property to an array of objects that are not T19PeriodHeads?:
public class T19Model:ITModel
{
public T19Item[] Items { get; set; }
public T19PeriodHead[] PeriodHeads { get; set; }
ITPeriodHead[] ITModel.PeriodHeads
{
get {return PeriodHeads;}
set {/* what to do here if value is not an array of T19PeriodHeads? */}
}
}
If you do not need a setter for the array property (maybe an Add method instead?) then you are fine.
I want to create a class that can take different types of value in a property. I am trying to do this using polymorphism, but I am not still learning how to do this properly, hence my request for advice.
I have a base class and two classes that inherit from it:
public abstract class BaseClass
{
public string Name { get; set; }
public Unit Unit { get; set; }
}
public class DerivedClassFloat : BaseClass
{
public float Value { get; set; }
public override string ToString()
{
return Value.ToString();
}
}
public class DerivedClassString : BaseClass
{
public string Value { get; set; }
public override string ToString()
{
return Value;
}
}
All is good, I can create a List and add different specialized subclasses. My problem comes when I need change the values of the items in my list:
foreach (var item in ListOfBaseClasses)
{
if(item is DerivedClassFloat)
((DerivedClassFloat) item).Value = float.NaN;
if (item is DerivedClassString)
((DerivedClassString) item).Value = string.Empty;
}
According to what I have read, that looks like a code smell. Is there a better way to access the value property of my derived classes based on the type I am trying to assign?
What about when you want to create the right subclass based on the value?
BaseClass newClass = null;
if (phenotype is DerivedClassFloat)
newClass = new DerivedClassFloat(){Value = 12.2};
if (phenotype is DerivedClassString)
newClass = new DerivedClassString(){Value = "Hello"};
I read about overriding virtual methods, but that works if I want to process the value, not to add or change it … maybe I am missing something?
I should make this more concrete, my apologies, I am not used to post question in this great site.
I need a property that is made of a list of attributes. Each attribute has a name and a value, but the value can be of different types. For example:
public class Organism
{
public string Name { get; set; }
public List<Attribute> Attributes { get; set; }
}
public class Attribute
{
public string AttributeName { get; set; }
public object AttributeValue { get; set; }
}
For a given organism I can have several attributes holding different value types. I wanted to avoid using the object type so that I don’t have to cast to the right type. I though property polymorphism was the solution to handle this case elegantly, but then I found myself using If ..Then which didn’t seem too different from casting in the first place.
If in your particular case you want to reset Value, you can define an abstract ResetValue method in the base class, which will be implemented by the derives classes.
As for your second case, you should check out Creational Design Patterns, and specifically the Factory and Prototype design patterns.
You can use generics to define the type and the implementing subclass will set the Value type to the type constraint:
public abstract class BaseClass<T>
{
public string Name { get; set; }
public Unit Unit { get; set; }
public T Value { get; set; }
public override string ToString()
{
return Value.ToString();
}
}
public class DerivedFloat : BaseClass<float> {}
public class DerivedString : BaseClass<string> {}
You can use Generics for this particular case:
public abstract class BaseClass<T>
{
public string Name { get; set; }
public Unit Unit { get; set; }
public T Value { get; set; }
}
public class DerivedClassFloat : BaseClass<float>
{
public override string ToString()
{
return Value.ToString();
}
}
public class DerivedClassString : BaseClass<string>
{
public override string ToString()
{
return Value;
}
}
Polymorphic behaviour works on abstraction. Based on what your trying to do, you can reduce code smell to moving as much of your variability in code to base classess.
i would suggest is instead of property write method like as follows. You can something like as follows.
public void setValue(string val, Type type);//move this to your base class
Class MyValue{
private string strVal;
private int intVal;
//constructor
MyValue(string val, Type type){
//check the type enum here and set the values accordingly
}
}
then when set values
foreach (var item in ListOfBaseClasses)
{
item.setValue = MyValue("",Type.INT);
}
I'm not quite sure what you are trying to achieve with this approach - the Value properties are not of the same type, there is also no Value property on the base class which suggests that other types derived from the base class might not have it at all.
If all of your classes require a Value property, then maybe it should be of the most general type object - you could put it onto the base class, but that would require casting the values in the derived classes.
But then you could have a NullObject to represent an absence of value that you could assign to the Value property for every derived class.
You can use the abstract factory pattern. Consider this example:
// Base class
class Button
{
protected Button()
{
}
public string Name { get; set; }
}
// Factory interface
public interface ButtonFactory
{
Button CreateButton();
}
// And the concrete classes
class WindowsButton : Button
{
// ...
}
class WindowsButtonFactory : ButtonFactory
{
public Button CreateButton()
{
return new WindowsButton();
}
}
class MacButton : Button
{
// ...
}
class MacButtonFactory : ButtonFactory
{
public Button CreateButton()
{
return new MacButton();
}
}
Furthermore, you can combine the abstract factory pattern with the strategy pattern to encapsulate the custom behaviors that change with type.
In a system for managing vocational training, I have a CourseBase abstract class, which I decided on using in favour of an ICourse interface because I'd prefer to avoid duplicating implementation code for all classes derived from the hypothetical, base Course entity. Each course has a list if subjects, with any subject defined by a SubjectBase abstract class. So, I have e.g.
public abstract class CourseBase : BaseObject
{
public IEnumerable<SubjectBase> Subjects
{
get { return new List<SubjectBase>(); }
}
}
public abstract class SubjectBase
{
public string Name { get; set; }
public string Description { get; set; }
public int ValidityPeriod { get; set; }
}
Now I want to add a concrete class, LocalCourse, which contains a collection of LocalCourseSubject objects, but because I'm not using an interface for CourseBase, I lose out on covariance, and I need to hide the abstract base's Subjects property with my new:
public class LocalCourse: CourseBase
{
public IEnumerable<LocalCourseSubject> Subjects
{
get { throw new NotImplementedException(); }
}
}
I'm sure I'm missing something very obvious here from an OO point of view, but the only solutions I can see are:
Completely omit Subjects from the abstract base, and only add a specifically typed collection property to derived classes.
Implement an interface such as ISubjectCollectionOwner in the abstract base as well as concrete classes.
Please excuse my dimness here, it's been a while since I've had the pleasure of encountering a design issue like this.
Why just not introduce a generic interface to abstract a Course? Sorry if I missed something obvious
public interface ICourse<TSubject>
{
IEnumerable<TSubject> Subjects { get; }
}
public abstract class CourseBase<TSubject>
: BaseObject,
ICourse<TSubject>
{
public IEnumerable<TSubject> Subjects
{
get { return new List<TSubject>(); }
}
}
public class LocalCourse
: CourseBase<LocalCourseSubject>
{
}
If Subject is a vital part of Course entity you should keep it within both ICourse and CourseBase as well, otherwise I would suggects abstracting it by ISubjectAware interface
Can't you just do this:
public abstract class CourseBase<T> where T : SubjectBase
{
public virtual IEnumerable<T> Subjects
{
get { return new List<T>(); }
}
}
public abstract class SubjectBase
{
public string Name { get; set; }
public string Description { get; set; }
public int ValidityPeriod { get; set; }
}
public class LocalCourse : CourseBase<LocalCourseSubject>
{
public override IEnumerable<LocalCourseSubject> Subjects
{
get { throw new NotImplementedException(); }
}
}
I think that would accomplish your short term goal, at any rate, assuming that the general pattern is that each CourseBase inheritor will have a collection of the same type of SubjectBase inheritor. But, if that is the case, this seems like a parallel inheritance hierarchy, which can sometimes be a code smell (not saying that it necessarily is -- I don't know all the details of the domain you're modeling).
I would like to force a set of classes to define three fields (of type string).
In an abstract class, I get that fields cannot be abstract and in an interface, I get an error saying that an interface cannot contain a field.
Is there no way to do this or am I not understanding this correctly? I'd rather not use methods because for some weird reason, the parentheses annoy me.
You can use properties for that:
interface MyInterface {
string Prop1 { get; set; }
string Prop2 { get; set; }
string Prop3 { get; set; }
}
Interface or abstract members force derived classes to provide code.
Fields don't have code.
You should use a property, which can be used like a field, but has code.
You can use Properties instead of fields:
// works similarly for Interfaces too
abstract class MyAbstractClass { public virtual string MyProperty1 { get; set; } }
class MyConcreteClass : MyAbstractClass { }
Then you can access MyProperty1 from any instance derived from MyAbstractClass:
MyAbstractClass obj1 = new MyConcreteClass;
obj1.MyProperty1 = "abcd";
Like everyone else says, use properties instead of fields, but you can do something like I interpreted in the comments as follows for read-only members:
abstract public class Base
{
abstract public string Foo { get; }
abstract public string Bar { get; }
abstract public string Baz { get; }
}
public class Derived : Base
{
public override string Foo { get { return "foo"; } }
public override string Bar { get { return "bar"; } }
public override string Baz { get { return "baz"; } }
}
If you want the fields to be modifiable later, you'll have to either use automatic properties or declare concrete backing fields and getter/setter pairs for each property.
I want:
public interface IBase
{
MyObject Property1 { get; set; }
}
public interface IBaseSub<T> : IBase
{
new T Property1 { get; set; }
}
public class MyClass : IBaseSub<YourObject>
{
public YourObject Property1 { get; set; }
}
But this doesn't compile. It gives the error:
//This class must implement the interface member IBase.Property1
Can anyone shed some light on this? I thought it should work..
Thanks
IBaseSub<T> requires IBase. I say "requires" because it more accurately reflects the practical implications than to say it "inherits" IBase, which implies overriding and other things that simply don't happen with interfaces. A class which implements IBaseSub<T> can actually be said to implement both, like so:
public class MyClass : IBase, IBaseSub<YourObject>
Going back to what I said about inheritance - there is no such thing with interfaces, which means just because both interfaces have a property with the same name, the derived one isn't overriding or hiding the base one. It means that your class must now literally implement two properties with the same name to fulfill both contracts. You can do this with explicit implementation:
public class MyClass : IBase, IBaseSub<YourObject>
{
public YourObject Property1 { get; set; }
MyObject IBase.Property1 { get; set; }
}
You need to implement the properties from both IBase and IBaseSub<YourObject>, since the latter expands on the former.
Using new in IBaseSub<T> does not let you "off the hook" regarding the necessity to have a MyObject Property1 { get; set; }. It simply allows you to declare another property named Property1 that implementors of IBaseSub<T> must have.
Since you cannot have two properties with the same name in MyClass, you will be forced to implement at least one of them explicitly:
public class MyClass : IBaseSub<YourObject>
{
MyObject IBase.Property1 { get; set; }
public YourObject Property1 { get; set; }
}