Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call constructor without new?

Tags:

c#

constructor

i know that string is like a class, and when creating a new string the string itself doesnt owe the value but only the value's pointer. but when creating a string there is no need to use the word new;

string a = "hello";

and not

string a = new string("hello");

I know that the second option is also possible but what i want to understand is why the first one?

Let's say I have a class name student which he's constructor gets a string. To create a new class I must use the saved word new.

student example = new student("Sabrina");

I tried overload oparator = but it is not possible.

How can I create a new class like a string does (without using the word new)?

student example = "Sabrina"; 
like image 220
Superzarzar Avatar asked Nov 30 '22 01:11

Superzarzar


2 Answers

You can use cast operator to implicitly:

    sealed class Student
    {
        public string Name
        {
            get;
            private set;
        }

        Student()
        {
        }

        public static implicit operator Student(string name)
        {
            return new Student
            {
                Name = name
            };
        }
    }

Then you can do Student student = "Sabrina";.

like image 146
Alessandro D'Andria Avatar answered Dec 04 '22 12:12

Alessandro D'Andria


Although you can get this done using an implicit operator, I would highly recommend not doing this at all. Strings are special animals in C# and they get special treatment - along with other special classes like int and float, you can create them without explicitly newing them up due to the way the C# compiler works:

var myInt = 0;
var myFloat = 0f;
var myString = "string";

However, this behavior is typically restricted to those special classes. Adding an implicit operator to do this is bad practice for multiple reasons:

  • It hides what is actually going on underneath. Are we creating a new Student under the hood when converting from a string?
  • It is unmaintainable. What happens when you have to add another parameter to the constructor to include the Student's ID number as well?
  • It eliminates the possibility of using implicitly-typed variables. You can't call var student = "name"; you must call Student student = "name".

The implicit operator paradigm breaks down very quickly. Though it's a cool thing to do, you're setting yourself up for a bad time down the road and making your code more difficult to read. I would highly advise just using new Student("name") like all other normal objects in C#.

like image 33
eouw0o83hf Avatar answered Dec 04 '22 13:12

eouw0o83hf