Search code examples
c#functioninput

How to get the value of an input variable from a function using OneOf C#


I want to get the input value from a function. I call the function:

Name=GetName(Paul)

Where Paul is a member of ClassA, ClassB or Class C. I want to use the following function to call other functions with Paul as an input depending on the class Paul is really in.

public static string GetName(OneOf<ClassA,ClassB,ClassC> input)
{
    var Variable = input.Match(
    ClassA => doSomethingWithA(input),
    ClassB => doSomethingWithB(input),
    ClassC => doSomethingWithC(input),
    );
}

When I try to input.Value or something like that, I just get the name of the class, but not Paul, which is unfortunate, because then I don't have the input I need for my functions doSomethingWith.

Has someone an idea how to solve this? It doesn't have to use the OneOf-Package.


Solution

  • You can use a lambda function based on the type of input and get the appropriate name accordingly.

    Refer the code below:

    using System;
    using OneOf;
    
    public class ClassA
    {
        public string Name { get; set; }
    
        public ClassA(string name)
        {
            Name = name;
        }
    }
    
    public class ClassB
    {
        public string Name { get; set; }
    
        public ClassB(string name)
        {
            Name = name;
        }
    }
    
    public class ClassC
    {
        public string Name { get; set; }
    
        public ClassC(string name)
        {
            Name = name;
        }
    }
    
    public class Program
    {
        public static void Main(string[] args)
        {
            var A = new ClassA("Paul");
            var B = new ClassB("John");
            var C = new ClassC("Sam");
    
            OneOf<ClassA, ClassB, ClassC> inputA = A;
            OneOf<ClassA, ClassB, ClassC> inputB = B;
            OneOf<ClassA, ClassB, ClassC> inputC = C;
    
            Console.WriteLine("Class A Name : "+GetName(inputA)); // Class A Name : Paul
            Console.WriteLine("Class B Name : "+GetName(inputB)); // Class B Name : John
            Console.WriteLine("Class C Name : "+GetName(inputC)); // Class C Name : Sam
        }
    
    
        /*
        * Method get Name given a OneOf from Class A , B , C
        */
    
        public static string GetName(OneOf<ClassA, ClassB, ClassC> input)
        {
            var variable = input.Match(
                classA => classA.Name,
                classB => classB.Name,
                classC => classC.Name
            );
    
            return variable;
        }
    }
    

    Refer to the working .netfiddle here