recreate instance in base class - c#

I was wondering if it is possible to change the type of an instance of a derived class in it's base class to another derived class from the same base . following I will try to explain it in a code .
public class ValueTypeClass
{
private string _Note;
private String _Name;
private nodeClass refrenceNode ;
//...
}
public class refrenceDBClass : valuetypeclass
{
//...
}
public class refrenceFileClass : valuetypeclass
{
//...
}
now each time the refrenceNode is changed I want to change the type of the instance based on the refrenceNode properties
Edit 1 :
Now I'm doing this by having another class which keeps the detail of refrencedbclass and refrencefileclass and everytime the refrencenode is changed I'm creating a new instance .
public class ValueTypeClass
{
private string _Note;
private String _Name;
private nodeClass refrenceNode ;
private detailClass detailInfo ;
//...
}
public class detailClass
{
//...
}
public class refrenceDBClass : detailClass
{
//...
}
public class refrenceFileClass : detailClass
{
//...
}

In C#, an instance never changes its type.
I don't understand the problem you want to solve with this, but I assume that you should aggregate this type you want to change, and create a new instance if some value changes. Like the strategy pattern, for instance.

You can not change the type of a managed .NET object. If you were encapsulating the object (in a wrapper - for example refrenceNode) you could swap the reference, but that is about it.
In some (limited) cases, you might be able to serialize/deserialize an encapsulated instance, changing the type in the process (only works for contract-based serializers, with compatible contracts; very unlikely). You certainly can't change the type of the current instance.
Re the edit; again, you can't change the type of how you expose the details, but with some casting you could make it work; vaguely, something like:
public class ValueTypeClass
{
private string _Note;
private String _Name;
private nodeClass refrenceNode;
public nodeClass ReferenceNode {
get {return refrenceNode;}
set {
if(refrenceNode == value) return; // nop
refrenceNode = value;
BuildDetailInfo();
}
}
private detailClass detailInfo;
public detailClass DetailInfo {get {return detailInfo;}}
private void BuildDetailInfo() {
// TODO: decide on the appropriate type (based on refrenceNode)
// and recreate detailInfo
}
}
It sounds like you should also be making use of polymorphism. If you are doing data-binding there are some other things you can do (with considerable effort) to make this more friendly, but it won't affect regular code.

Related

What is the use of private constructor in abstract class in c#?

I face the below question in the interview.
Q1.Can we have a private constructor in the abstract class?
Answer- Yes, I gave an answer we can have then he again ask why and what is the use of the private constructor.
I'm not able to answer to this cross-question. Can anybody explain this? with practically in c# will great help.
I can think of two uses:
Firstly, for chaining. You might have multiple protected constructors, but want to execute common code in all of them:
public abstract class Foo
{
protected Foo(string name) : this(name, 0)
{
}
protected Foo(int value) : this("", value)
{
}
private Foo(string name, int value)
{
// Do common things with name and value, maybe format them, etc
}
}
The second use would be to make it so that the only possible derived classes would be nested classes, which have access to private members. I've used this before when I want to enforce a limited number of derived classes, with instances usually exposed via the base class
public abstract class Operation
{
public static readonly Operation Add { get; } = new AddOperation();
public static readonly Operation Subtract { get; } = new SubtractOperation();
// Only nested classes can use this...
private Operation()
{
}
private class AddOperation : Operation
{
...
}
private class SubtractOperation : Operation
{
...
}
}

C# - adding data custom checks to the compiling process

Context: a simple base class which holds a name and a couple methods.
public abstract class BaseElement
{
public string Name { get; set; }
public abstract object GetDescription();
public abstract void DoStuff();
}
A developer could subclass BaseElement, he will have to implement GetDescription() and DoStuff(), but can completely forget to assign a value to the Name property.
A simple solution would be to change the class this way:
public abstract class BaseElement
{
public string Name { get; private set; }
public abstract object GetDescription();
public abstract void DoStuff();
private BaseElement()
{
}
public BaseElement(string name)
{
Name = name;
}
}
So, this way when you subclass you are forced to assign a name.
Still, you can always go as far as to use null or "".
Ok, then I can add a parameter check into the ctor and throw the relative exception, but...you'll discover the mistake only at run time, after you try to use the derived class.
So, the question: is it possible to add compilation-time rules to instruct the compiler to check for variables possible values, so that the problem is discovered at compile time and not at run time?
How about like this?
public string Name
{
get { return _name; }
private set
{
if (!string.IsNullOrWhiteSpace(value))
_name = value;
else
{
throw new Exception("Exception");
}
}
}

Object read only when accessed through/as another object's field

Situation:
I often run into this problematic and never know how to solve it. Though I don't know where and how to look for answer.
So here it is. When you store some objects into other objects you can have them as readonly, or just with a getter, which is the same. This way you cannot change the value of a MyInt in
public class ClassA {
public readonly int MyInt;
public string MyString;
}
and no problem if I want to put this in a container as follows:
public class ClassB {
public readonly ClassA MyClassA;
public string MyString;
}
This will still work as expected. MyInt is readonly and MyStringA is not.
Problem:
But I can still get MyClassA and set MyClassA.MyStringA.
Is there a way to have a "stricter" readonly system?
With the above example I would like MyClassA's fields to be all readonly if MyClassA is.
The only solution I can think of is to have another class MyClassAreadonly. But that seems ugly and not not convenient.
Context:
The reason why I am looking for this behavior is that I want MyClassB.MyString to add logic (like firing an event) before setting MyClassB.MyClassA.MyString. So another solution is to simply not show ClassB.MyClassA by setting it as private. But that is nice to being able to retrieve MyClassA! But if I retrieve it and modify it I miss the ClassB logic!
PS: Despite I can't figure it out, I hope to have been clear enough.
You can wrap properties of ClassA into properties of ClassB like this:
public class ClassB
{
private readonly ClassA _myClassA = new ClassA();
private string _myString;
public string MyString
{
get
{
// your logic here
return _myString;
}
set
{
// your logic here
_myString = value;
}
}
public string MyStringA { get { return _myClassA.MyString;}}
public int MyIntA { get { return _myClassA.MyInt; }}
}
How about adding an event to ClassA that ClassB can then handle in order to implement the additional logic?
public class ClassA
{
public readonly int MyInt;
private string _myString;
public string MyString
{
get
{
return _myString;
}
set
{
_myString = value;
if (MyStringChanged != null)
{
MyStringChanged(this, new EventArgs());
}
}
}
public event EventHandler MyStringChanged;
}
public class ClassB
{
public readonly ClassA MyClassA;
//It sounds like you wanted to use ClassB.MyString to manipulate ClassA.MyString, so you probably won't need this anymore?
//public string MyString;
public ClassB()
{
MyClassA = new ClassA();
MyClassA.MyStringChanged += new EventHandler(MyClassA_MyStringChanged);
}
private void MyClassA_MyStringChanged(object sender, EventArgs e)
{
//Add your logic here
}
}
"Deep" immutability
As stated in a comment by #Damien_The_Unbeliever, here is a perfect "answer" to my question. I put answer between quote marks because there is no built-in solution for the moment in C#.
The closest alternative to address my issue will be to have an Immutable facade for the objects (MyClassA) I want to use this way.
Thanks Damien.
Another read on the subject: http://www.bluebytesoftware.com/blog/2007/11/11/ImmutableTypesForC.aspx

Class Design - Base class with Generic Descendant

I have the following classes
class GridBase
{
public object DataSource { get; set; }
}
class GenericGrid<T> : GridBase
{
public new T DataSource { get; set; }
}
Both GridBase and Generic Grid classes can be instantiated and one can descend from either as well.
Is this considered the correct/accepted way to implement such a hierarchy?
Or should you go the extra mile and implement it like the following
class GridBase
{
protected object dataSource;
public object DataSource { get { return dataSource; } set { dataSource = value; } }
}
class GenericGrid<T> : GridBase
{
public new T DataSource { get { return (T)dataSource; } set { dataSource = value; } }
}
The same applies to non generic classes when a property is re-introduced in a descendant, I'm just using a generic example here.
Another case and question
abstract class SomeBase
{
protected abstract void DoSomething();
}
class Child : SomeBase
{
protected override void DoSomething()
{
/* Some implementation here */
}
}
The situation here is that framework "X" declares SomeBase allowing you to define your own descendants. The classes they create (at run time) then descend from your class (Child in the this case). However, they don't call your DoSomething() method, from their implementation of DoSomething().
On their part, they can't blindly call base.Dosomething() either because the typical case is that the class they generate normally descends from SomeBase and since the method is abstract that's not valid. (Personally, I don't like this behavior in C#).
But anyway, is that good or accepted design, that is not calling base.xxx(), especially when the the "intent" seems to contradict?
EDIT From a framework design perspective. Is it ok/acceptable that it does this? If not how would it be designed so as to either prevent such a case or better impart their intent (in both cases).
I would prefer something like this:
interface IGrid {
object DataSource { get; }
}
interface IGrid<T> {
T DataSource { get; }
}
public Grid : IGrid {
public object DataSource { get; private set; }
// details elided
}
public Grid<T> : IGrid<T> {
public T DataSource { get; private set; }
object IGrid.DataSource { get { return this.DataSource; } }
// details elided
}
Note that I am NOT inheriting from Grid.
For the DataSource question I prefer the following pattern
abstract class GridBase {
public abstract object DataSource { get; }
}
class GenericGrid<T> : GridBase {
private T m_data;
public override object DataSource {
get { return m_data; }
}
public T DataSourceTyped {
get { return m_data; }
set { m_data = value; }
}
}
Reasons
Having the GridBase.DataSource member be writable is type unsafe. It allows me to break the contract of GenericGrid<T> by setting the value to a non-T instance
This is more of a matter of opinion but I dislike the use of new because it often confuses users. I prefer the suffix ~Type" for this scenario
This only requires the data be stored once
Doesn't require any unsafe casting.
EDIT OP corrected that GridBase and GenericGrid are both usable types
In that case I would say you need to reconsider your design a bit. Having them both as usable types opens you up to very easy to expose type errors.
GenericGrid<int> grid = new GenericGrid<int>();
GridBase baseGrid = grid;
baseGrid.DataSource = "bad";
Console.Write(grid.DataSource); // Error!!!
The design will be a lot more reliable if separate the storage from the access of the values in a manner like my original sample. You could extend it further with the following code to have a usable non-generic container
class Grid : GridBase {
private objecm m_data;
public override object DataSource {
get { return m_data; }
}
public object DataSourceTyped {
get { return m_data; }
set { m_data = value; }
}
}
The second form of the generic inheritance (casting the base class' attribute) is more correct as it does not violate Liskov Substitution Principle. It is conceivable that an instance of the generic class is cast into base class and accessing Data through the base class points to a different property. You will need to keep both in sync in order for the derived class to be substitutable for the base class.
Alternatively, you can implement some sort of a strategy pattern where the base class asks for the Data property from the derived class, in order to avoid awkward downcasting. This is what I had in mind:
public class Base {
private readonly object m_Data; //immutable data, as per JaredPar suggestion that base class shouldn't be able to change it
publlic Base(object data) {
m_Data = data;
}
protected virtual object GetData() {return m_Data;}
public Object DataSource {get {return GetData();}}
}
public class Derived<T> : Base {
private T m_Data;
public Derived():base(null){}
protected override object GetData() {return m_Data;}
protected new T Data {return m_Data;}
}
With regards to the second question, I am note sure I understand the question. Sound like the problem you are having is to with the framework not calling the abstract method when it generates a proxy at runtime, which is always legal in abstract classes, as the only way for that code to execute is through a derived class which must override the abstract method.

C# Inheritance question

I have a class that has private fields... (cars)
I then inherit from this class... (Audi)
In the (Audi) class, when I type this. in the constructor...
the private fields are not available...
Do I need to do anything special to expose this private fields in (cars) class so that they are accessible via this. in (Audi class)?
One (bad) option is to make the fields protected - but don't do this; it still breaks proper encapsulation. Two good options:
make the setter protected
provide a constructor that accepts the values
examples:
public string Name { get; protected set; }
(C# 2.0)
private string name;
public string Name {
get { return name; }
protected set { name = value; }
}
or:
class BaseType {
private string name;
public BaseType(string name) {
this.name = name;
}
}
class DerivedType : BaseType {
public DerivedType() : base("Foo") {}
}
Philippe's suggestion to declare the fields as protected instead of private will indeed work - but I suggest you don't do it anyway.
Why should a derived class care about an implementation detail of how the data is stored? I suggest you expose protected properties which are (currently) backed by those fields, instead of exposing the fields themselves.
I treat the API you expose to derived classes as very similar to the API you expose to other types - it should be a higher level of abstraction than implementation details which you may want to change later.
You should declare them as "protected" instead of private
You are probably looking for a concept called constructor inheritance. You can forward arguments to the base classes constructor - see this example, where the Audi has a flag indicating whether it's an S-Line edition or not:
namespace ConstructorInheritance
{
abstract class Car
{
private int horsePower;
private int maximumSpeed;
public Car(int horsePower, int maximumSpeed)
{
this.horsePower = horsePower;
this.maximumSpeed = maximumSpeed;
}
}
class Audi : Car
{
private bool isSLineEdition = false;
// note, how the base constructor is called _and_ the S-Line variable is set in Audi's constructor!
public Audi(bool isSLineEdition, int horsePower, int maximumSpeed)
: base(horsePower, maximumSpeed)
{
this.isSLineEdition = isSLineEdition;
}
}
class Program
{
static void Main(string[] args)
{
Car car = new Audi(true, 210, 255);
// break here and watch the car instance in the debugger...
}
} }

Categories