Dan
Dan

Reputation: 67

C# custom variables

I was experimenting with making a custom variables but got stuck.

I'm still new to C# so it's only expected for me to not know what's happening, I guess..

struct MyCustomStringVariable
{
    public static implicit operator MyCustomStringVariable(string input)
    {
        return input;
    }
}

class Program
{
    static MyCustomStringVariable myCustomString = "This is a string!";

    static void Main(string[] args)
    {
        Console.WriteLine(myCustomString);
        Console.ReadLine();
    }
}

The following exception is thrown

System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was thrown.'

Upvotes: 2

Views: 4180

Answers (2)

Igor
Igor

Reputation: 62213

This is because the code is stuck in an infinit loop. Your implicit operator will call itself because it returns the original input string which does not throw an exception because of the defined operator.

public static implicit operator MyCustomStringVariable(string input)
{
    return input; // returning string type will call this method again
}

should be

public static implicit operator MyCustomStringVariable(string input)
{
    // and use input somewhere on the returned type
    return new MyCustomStringVariable(); 
}

That said there is probably no reason for you to define a type named MyCustomStringVariable but that is hard to tell because you never share the code for this or how you intend to use it.


My final goal is to visualize the process of making a string variable in my head so that I can better understand the concept behind it.

I am not sure how your custom struct or its implicit operator fit in with this goal. Why not just use the type string?

static string myCustomString  = "This is a string!";

Upvotes: 4

Soader03
Soader03

Reputation: 351

It's because the implicit operator is called recursively. You'll need to implement your structure as so, encapsulating your string variable somehow.

struct MyCustomStringVariable
{
    private string value;

    public MyCustomStringVariable(string input)
    {
        value = input;
    }

    public static implicit operator MyCustomStringVariable(string input)
    {
        return new MyCustomStringVariable(input);
    }

    public string GetValue()
    {
        return value;
    }
}

Then, calling it like

Console.WriteLine(myCustomString.GetValue());

You can refer to the documentation here.

Upvotes: 1

Related Questions