2

I'm very fresh to C# Currently learning Operator overloading i'm trying to do something like this:

string val = 500; (I can't implicitly)

and then

Number n1 = val;

I manages to get the Number n1 = someintvalue, for instance:

Number n1 = 500;

like this:

public struct Number
{
    public int Value { get; set; }
    public Number(int Val)
    {
        Value = Val;
    }
    public static implicit operator Number(int num)
    {
        return new Number(num);
    }
}

However, when trying to make Number n1 = val; (when val is a string) I simply cant since the first line cant compile:

string val = 500;

and the following wont work:

public static implicit operator string(int A)
{
    return new string(A);
}

because of 1 error which i can not understand
1)User-defined conversion must convert to or from the enclosing type

by the way i get the idea of op overload
underthis specific case of: return new Number(num); I simply init the ctor
still need some more fundemental understanding thx ahead!

2
  • Side note: do not use struct unless you understand the difference between it and class, and explicitly need a struct. Mutable structs can cause all sorts of problems that are usually unnecessary. Commented Mar 28, 2016 at 14:40
  • Plus, string val = 500; is poor practice. If you want a string then use a string: string val = "500"; C# is a strongly-typed language and should be treated as such - adding multiple type conversion overloads erodes that type safety. Commented Mar 28, 2016 at 14:42

1 Answer 1

5

I presume the function you quote is within the Number class. You have added a conversion operator from an int to a string within that class, which is not legal. You can only add operators that convert to or from the type they're defined in, such as:

public static implicit operator string(Number A)
{
    return new string(A.Value);
}

which will fail because string does not have a constructor that takes an int. You could do:

public static implicit operator string(Number A)
{
    return A.ToString();
}

But the standard way to "convert" to a string is to overload the ToString method, which the compiler often calls automatically when a conversion to string is requested:

public override string ToString()
{
    return Value.ToString();
}
Sign up to request clarification or add additional context in comments.

2 Comments

I get what you did here. However, I do not understand how to make the string val = 500; within the void Main
500 is an integer, not a string. There is no implicit conversion from int to string, so you need either string val = "500"; or string val = 500.ToString();. C# is a type-safe language. Don't try to use it like JavaScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.