What does "this" refer to in the second paragraph of the code?

In this code snippet, this.Var1 represents 10, which is quite evident.

class MyClass
{
int Var1 = 10;
public int ReturnMaxSum(int Var1)

  {    
   return Var1 > this.Var1
   ? Var1 
   : this.Var1;
  }
}

class Program
{
static void Main()
  {
    MyClass me = new MyClass ();
    Console.WriteLine($"Max: { mc.ReturnMaxSum(30) }");
    Console.WriteLine($"Max: { mc.ReturnMaxSum(S) }");
  }
 }

second paragraph

  • Negative value if the current object is less than the parameter
    object;
  • positive value if the current object is greater than the parameter
    object;
  • zero if the two objects are equal when compared.

There is a question here: What is the current object? TheValue has not been assigned an initial value, so how can it be compared with the input parameter mc.Value?

class MyClass;IComparable
{
public int TheValue;
public int CompareTo(object obj) 
 {
   MyClass mc= (MyClass)obj;
   if (this.TheValue < mc.TheValue) return -1;
   if (this.TheValue > mc.TheValue) return 1;
   return 0;
  }
}

>Solution :

If a field is not assigned any value, it will be initialized with a default value, which is 0 for all integral numeric types.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/default-values

Leave a Reply