Avinash Reddy
Avinash Reddy

Reputation: 937

How Int32 datatype is directly assigned?

Int32 i = new Int32();
i = 10;

Here I is struct data type and we are assigning a value to it directly where

struct myst
{
}

myst mySt = new myst();
myst = 10;

Here I need a property to assign so the question is how Int32 is able to assign a value to struct object directly?

Upvotes: 0

Views: 237

Answers (2)

TheGeneral
TheGeneral

Reputation: 81493

If i understand you correctly (and i have no idea if i do). To assign implicitly to a Custom Type, you will need to implement an Implicit Operator

implicit operator (C# Reference)

The implicit keyword is used to declare an implicit user-defined type conversion operator. Use it to enable implicit conversions between a user-defined type and another type, if the conversion is guaranteed not to cause a loss of data.

Example

struct FunkyStruct 
{

   public FunkyStruct(int d) { val = d; }
   public int val;
   // ...other members

   // User-defined conversion from Digit to double
   public static implicit operator int(FunkyStruct d)
   {
      return d.val;
   }
   //  User-defined conversion from double to Digit
   public static implicit operator FunkyStruct(int d)
   {
      return new FunkyStruct(d);
   }
}

Usage

public static void Main()
{
   FunkyStruct s;
   s = 10;
   Console.WriteLine(s.val);
}

Update

Console.WriteLine(s) and it should print 10 just like int how can I achieve this

It already does

Full Demo Here

Upvotes: 6

kAsdh
kAsdh

Reputation: 366

myst is not Int32 . One thing you can do here is , create Int32 variable inside struct and assign value for that.

 struct myst
    {
       public Int32 a { get; set; }
    }


 static void Main(string[] args)
        {     
            myst mySt = new myst();
            mySt.a = 10;
        }

Upvotes: 1

Related Questions