Vikash Singh Gangwar
Vikash Singh Gangwar

Reputation: 31

How to create sealed class like String class in .net so that we can assign value without creating instance like string str="abc"

I want to create a class like string class in .NET. String is a sealed class and we can directly assign values to this class like string str="Cat";.

How can I create a sealed class like this?

Upvotes: 2

Views: 648

Answers (1)

Muepe
Muepe

Reputation: 671

The fact that string can be assigned from a string-literal is not because the class is sealed. See the documentation for a description: http://msdn.microsoft.com/en-us/library/88c54tsw(v=VS.100).aspx

For string it works because the string literal is by default converted into a string-object but you can achieve the same for your own class with an implicit operator:

public class MyCustomClass
{
    string mString;

    public MyCustomClass(string str)
    {
        mString = str;
    }

    /* Structure of the implicit operator:
     * modifier static implicit operator destinationType(sourceType value)
     */

    public static implicit operator MyCustomClass(string value)
    {
        MyCustomClass cls = new MyCustomClass(value);
        return cls;
    }

    public static implicit operator string(MyCustomClass cls)
    {
        if (cls == null)
            return null;

        return cls.mString;
    }
}

Then for example you can use the following:

MyCustomClass cls = "Hello!";
string str = cls;

Upvotes: 10

Related Questions