0

I want to know the difference between calling a method within the same class using 'this.MethodName' and just the 'MethodName' in C#.

First Option

public class Transaction
    {
        public bool PerformTransaction(Model model)
        {
            //Calling the method name using 'this'
            var refNumber = this.GetTransactionReferenceNumber(model);
            //Method Implementation
        }
        
        private string GetTransactionReferenceNumber(Model model)
        {
            //Method Implementation
        }
    }

Second Option

public class Transaction
    {
        public bool PerformTransaction(Model model)
        {

            //Calling the method using it's name(without using 'this' keyword)
            var refNumber = GetTransactionReferenceNumber(model);
            //Method Implementation
        }
        
        private string GetTransactionReferenceNumber(Model model)
        {
            //Method Implementation
        }
    }

Which option should I use to call methods within the same class?. What is the difference between both options? and what is the best practice?

  • 2
    it does not matter. it's 100% the same. the `this.`-qualifier is redundant. chose whichever you prefer optically, i opt for the second. (addendum: you'd only ever need the qualifier if there's something else with the same name, like a `var GetTransactionReferenceNumber = "";` or something) – Franz Gleichmann Aug 03 '20 at 16:26
  • One common use of `this` is for initializing class fields from constructor parameters named the same as the fields. In that case, you do need to specify which is which when assigning, ex: `this.connectionString = connectionString;` – insane_developer Aug 03 '20 at 16:30

0 Answers0