How design a class?

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
 
A

Arne Vajhøj

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
 
A

Arne Vajhøj

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
 
B

Brian Cryer

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top