-1

I have a problem with switch. The user can select one of few options. Then based on the user's choice, I have to change a variable type.

var train = new Propagation();

switch (alghoritm)
{
    case 1:
       train = OtherPropagation();
    case 2:
       train = OtherPropagation2();
    case 3:
       train = OtherPropagation3();
    default:
       train = Propagation();
}

C# has static variable types, so it's impossible for me to change it, but based on choice, the rest code works diffrently.

Do you have any ideas?

Thanks for your help!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Caran
  • 15
  • 7

3 Answers3

3

You can create a common interface for all theses types (that calls to OtherPropagation, OtherPropagation2 return). Then you can use this common interface as the type of train.

E.g. Let's call this IPropagation

public interface IPropagation
{
    // place here the common methods
}

Then change the return type of your methods, OtherPropagation, OtherPropagation2 etc. to be of IPropagation. Furthermore, you have to implement this interface for all the types that currently these methods return.

Last, change the type of variable train to be of IPropagation.

Christos
  • 53,228
  • 8
  • 76
  • 108
1

if Propagation is base class of others, this works:

class Propagation { }
class Propagation1 : Propagation  { }
class Propagation2 : Propagation  { }
class Propagation3 : Propagation  { }


Propagation GetPropagation(int alghoritm)  //return base class
{
    Propagation train;
    switch (alghoritm)
    {
    case 1:
     train = Propagation1();
    case 2:
     train = Propagation2();
    case 3:
     train = Propagation3();
    default:
     train = Propagation();
    }
     return train;
}

if all classes have a common interface IPropagation, then this works:

class Propagation : IPropagation { }
class Propagation1 : IPropagation  { }
class Propagation2 : IPropagation  { }
class Propagation3 : IPropagation  { }

IPropagation GetPropagation(int alghoritm)  //return interface
{
    IPropagation train;
    switch (alghoritm)
    {
    case 1:
     train = Propagation1();
    case 2:
     train = Propagation2();
    case 3:
     train = Propagation3();
    default:
     train = Propagation();
    }
     return train;
}
Dongdong
  • 2,208
  • 19
  • 28
-1

You can try dynamic data type.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic

Shing
  • 62
  • 6
  • How is this helpful for the code that happens after the switch? – Rotem Jan 22 '20 at 15:18
  • 1
    The `dynamic` keyword should be avoided. Is the use of dynamic considered a bad practice? - Stack Overflow - https://stackoverflow.com/questions/31859016/is-the-use-of-dynamic-considered-a-bad-practice – akop Jan 22 '20 at 16:01