how to find type of object

  • Thread starter Thread starter buller
  • Start date Start date
Correct.  A square is not an extension of a rectangle, it is a constraint on
a rectangle, so making Square derived from Rectangle is bad.  Not all
rectangles are squares, so making Rectangle derived from Square is very bad.

Well, I don't think deriving Square from Rectangle is necessarily
bad. At least a square is a rectangle and had the blogger done the
derivation in that direction I wouldn't be beating down his argument.
Maybe that's the subject of another debate though.
 
It looks to me like everyone missed the actual question here. Maybe we can
change this to:

private class A {}
private class B : A {}
private class C : B {}

// this is what you want I think:
if (list.GetType() == typeof(B))

The problem with this is that it is probably pretty slow. One thing you
could do is define an enum that add a property to A and then the children can
override it.

private enum FigureType { Unknown, Square, Rectangle, Circle }

private class A {
public virtual FigureType FigureType { get { return FigureType.Unknown; } }
}

private class B {
public override FigureType FigureType { get { return FigureType.Square; } }
}

private class C {
public override FigureType FigureType { get { return FigureType.Rectangle; } }
}

//....

if (list.FigureType == FigureType.Square)

This will just be a virtual method call.
 
Bryan said:
It looks to me like everyone missed the actual question here. Maybe we
can
change this to:

private class A {}
private class B : A {}
private class C : B {}

// this is what you want I think:
if (list.GetType() == typeof(B))


That's exactly what Peter suggested about four weeks ago.
The problem with this is that it is probably pretty slow. One thing you
could do is define an enum that add a property to A and then the children
can
override it.

private enum FigureType { Unknown, Square, Rectangle, Circle }

That isn't extensible.
private class A {
public virtual FigureType FigureType { get { return
FigureType.Unknown; } }
}

private class B {
public override FigureType FigureType { get { return
FigureType.Square; } }
}

private class C {
public override FigureType FigureType { get { return
FigureType.Rectangle; } }
}

//....

if (list.FigureType == FigureType.Square)

This will just be a virtual method call.
 
It looks to me like everyone missed the actual question here.  Maybe wecan
change this to:

I knew exactly what the question was. I choose to provide alternate
way of looking at the situation that made the question moot.
 
Back
Top