Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I specify a constructor value using the = operator?

When making a string in C#, you'd do string foo = "bar"; string being a class, and the value "bar" got passed to the class using the = operator. How was that done? Could you do this in your own class?

I know this is doable in C++ as such.

class someClass {
public:
    someClass(int someInt) {
        // Do Stuff
    }

};

int main() {
    someClass classInst = 123;
}

But what would be the C# equivalent?

like image 693
Shayna Avatar asked Dec 07 '25 06:12

Shayna


2 Answers

There are two parts to this question:

  • How string literals work
  • How to do the same kind of thing for your own class

String literals

The expression "bar" is already a value of type string. The assignment operator here is just copying the reference, as it does for anything else. String literals cause string objects to be created where possible (but reused, so if you have that code in a loop, there's only a single string object). There's some subtlety here for interpolated string literals around FormattableString, but I'll ignore that for the purpose of this question.


Creating your own literal-like syntax

You can't make the assignment operator implicitly call a constructor directly, no. You could add an implicit conversion from int to SomeClass, but I would generally discourage that.

Here's a complete example in case you really want to do it, but it's really not idiomatic. By the time you have implicit conversions, you make it harder to reason about overload resolution for example - and anyone reading your code has to know that there is a user-defined implicit conversion.

using System;

class SomeClass
{
    public int Value { get; }

    public SomeClass(int value) => Value = value;

    public static implicit operator SomeClass(int value) =>
        new SomeClass(value);
}

public class Program
{
    static void Main()
    {
        SomeClass x = 123;
        Console.WriteLine(x.Value);
    }
}

Note that if the target-typed new feature comes to pass in C# 8, you'd be able to write:

SomeClass x = new(123);

... so you'd at least save the duplication there, even for fields.

like image 172
Jon Skeet Avatar answered Dec 09 '25 18:12

Jon Skeet


You can define implicit conversions between the two types: int and SomeClass like below:

// User-defined conversion from SomeClass to int
public static implicit operator int(SomeClass someClass)
{
    return someClass.SomeInt;
}
//  User-defined conversion from int to SomeClass
public static implicit operator SomeClass(int someInt)
{
    return new SomeClass(someInt);
}

Those methods should be defined in SomeClass declaration.

For more information about implicit conversion check this link.

like image 21
CodeNotFound Avatar answered Dec 09 '25 19:12

CodeNotFound



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!