How design a class?

  • Thread starter Thread starter Anders Eriksson
  • Start date Start date
A

Anders Eriksson

If I have a structure that look like this

foo
bar1 or
bar2 or
bar3

I. e. foo can contain either a bar1 or a bar2 or a bar3.

How would class foo look like?

// Anders
 
If I have a structure that look like this

foo
bar1 or
bar2 or
bar3

I. e. foo can contain either a bar1 or a bar2 or a bar3.

How would class foo look like?

The obvious would be an abstract base class BarBase or an interface
IBar.

Arne
 
The obvious would be an abstract base class BarBase or an interface
IBar.

Demo:

using System;

namespace E
{
public abstract class Bar
{
public abstract void RealM();
public void M()
{
RealM();
}
}
public class Bar1 : Bar
{
public override void RealM()
{
Console.WriteLine("Bar1 here");
}
}
public class Bar2 : Bar
{
public override void RealM()
{
Console.WriteLine("Bar2 here");
}
}
public class Foo
{
private Bar bar;
public Foo(Bar bar)
{
this.bar = bar;
}
public void MM()
{
bar.M();
}
}
public class Program
{
public static void Main(string[] args)
{
Foo foo1 = new Foo(new Bar1());
foo1.MM();
Foo foo2 = new Foo(new Bar2());
foo2.MM();
Console.ReadKey();
}
}
}

Arne
 
Anders Eriksson said:
If I have a structure that look like this

foo
bar1 or
bar2 or
bar3

I. e. foo can contain either a bar1 or a bar2 or a bar3.

How would class foo look like?

Given that you used the word "structure", I wonder whether you are thinking
of what in C/C++ would be a union? Union's are not supported in C# (although
if you google for it you can find some good simulations - although I suspect
these are only viable with value types not reference types). So you are left
with inheritance as the only viable way forward - see Arne's post.
 
Back
Top