Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Implicit/Explicit Type Conversion

I have a simple scenario that may or may not be possible. I have a class that contains an integer, for this purpose I'll make it as simple as possible:

public class Number
{
    public int Value {get; set;}
    public string Name {get; set;}
}

public static void Print(int print)
{
    Console.WriteLine(print);
}

public static string Test()
{
    Number num = new Number (9, "Nine");
    Print(num); //num "overloads" by passing its integer Value to Print.
}

// Result
// 9

How do I make the Test() function work as I have coded it? Is this even possible? I think this can be done with the explicit/implicit operator but I can't figure it out.

like image 498
Mike Avatar asked Feb 21 '11 04:02

Mike


2 Answers

Try something like this

    public static implicit operator int(Number num)
    {
        return num.Value;
    }
like image 193
CriticalImpact Avatar answered Oct 27 '22 00:10

CriticalImpact


class Number
{  
    public static implicit operator int(Number n)
    {
       return n.Value;
    }
}
like image 20
Mike Avatar answered Oct 27 '22 01:10

Mike