0

I know casting is not inherently bad practice, but is it bad in this situation?

I have the following class hierarchy, and the cast at the end.

 public class A<T> { public A(string name, T value) { Name = name; Value = value; } public string Name { get; } public T Value { get; } } public class B : A<double> { public B(string name, double value, string expression) : base(name, value) { Expression = expression; } public string Expression { get; } } public class C { public C(A<double> a) { _a = a; } public string Name { get { return _a.Name; } } public double Value { get { return _a.Value; } } protected A<double> _a; } public class D : C { public D(B b) : base(b) { } public string Expression { get { return ((B)_a).Expression; } } } 

The line in question: public string Expression { get { return ((B)_a).Expression; } }

14
  • 1
    Your constructor of D can take an instance of B and pass that to base constructor because B is a subclass of A<double> so id say s Commented Jun 14, 2018 at 22:23
  • 1
    Also you haven't actually asked a question... Commented Jun 14, 2018 at 22:25
  • @Dave The question is hidden in the first sentence: "Is this bad practice" Commented Jun 14, 2018 at 22:27
  • 2
    IMO, the bad practice here is a field that isn’t private Commented Jun 14, 2018 at 22:35
  • 1
    Encapsulate it with a property or method Commented Jun 14, 2018 at 22:41

2 Answers 2

3

Yes this is bad practice; like all downcasting (sometimes necessary to be sure; but that doesn't make it good).

The following code will generate a runtime exception:

A<double> myA = new A<double>("Test", 1.0d); D test = new D(myA); var boom = test.Expression; //InvalidCastException 

Whereas with a different structure that wouldn't even compile. For example, modifying D to take a B instead of an A<double>

Sign up to request clarification or add additional context in comments.

Comments

1

Try this, make the C class generic

public class C<T> where T : A<double> { public C(T thing) { _thing = thing; } protected T _thing; } 

Then D can be an instance of C with a generic argument of B

public D : C<B> { Public string Expression { get {return _thing.Expression;}} } 

I'm on my phone so please forgive.sny formatting or typo issues

1 Comment

This makes it all look a bit nicer imo but with your edit to your code, I'd say it's fine with the cast and your ctor ensures that the cast with succeed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.