ManInMoon
ManInMoon

Reputation: 7005

Can I create a delegate for the entire class c#

I have used delegates to represent methods - but I now have many classes that have same methods (but different code in those methods).

Is there a way to delegate the entire class?

Pseudo code:

class myModelA
{
     void update()
     {

     }
}

class myModelB
{
     void update()
     {

     }
}



delegate class myModel;

if (x==1)
     myModel = myModelA;
else
     myModel = myModelB;


myModel.update();

I know I can delegate the "üpdate" method BUT in real world I have lots of methods and I would rather just simply delegate the class.

EDIT1 based on Jon Skeet's answer

BUT how do I declare a public variable? (non public variables compile OK)

public interface IModel
{
    double myDouble; <<<< this gives an error
    void Update();
}

public class MyModelA : IModel
{
    public double myDouble;
    public void Update() { ... }
}

public class MyModelB : IModel 
{
    public double myDouble;
    public void Update() { ... }
}

Upvotes: 0

Views: 204

Answers (2)

As Jon Skeet, I think you need to use interfaces. A little changed code from

http://www.dotnetperls.com/interface

    using System;

    interface IPerl
    {
        void Read();
    }

    class TestA : IPerl
    {
        public void Read()
        {
        Console.WriteLine("Read TestA");
        }
    }

    class TestB : IPerl
    {
        public void Read()
        {
        Console.WriteLine("Read TestB");
        }
    }

    class Program
    {
        static void Main()
        {
        IPerl perl = new TestA(); // Create instance.
        perl.Read(); // Call method on interface.
        }
    }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503649

No, in this case you don't want a delegate - you want an interface.

You create an interface which all of your classes implement:

public interface IModel
{
    void Update();
}

public class MyModelA : IModel
{
    public void Update() { ... }
}

public class MyModelB : IModel 
{
    public void Update() { ... }
}

Then:

IModel model;
if (x == 1)
{
    model = new MyModelA();
}
else
{
    model = new MyModelB();
}
model.Update();

Upvotes: 8

Related Questions