-2

Okay, so still very new to C#, so sorry if this is obvious...

There is some code I can't follow that was created by someone who is much better at C#than I am.

We have a class, call it "CC", and it has a number of fields, one of which is "FORM_NBR".

So, in a nutshell:

public class CC
    {
    public CC();

    //Many, many fields...
    ...
    public long FORM_NBR { get; set; }
    ...
    }

At some point, an object is created...

CC c = new CC();

and then this line is called:

c.FORM_NBR = c.FORM_NBR.GetCheckDigit(' ');

Now, there is this function deep in the library we inherited:

public static short GetCheckDigit(this long nFormNbr, char chFormTypCd)
{
    short nCkDgt = 0;   // Default to 0

    switch (chFormTypCd)
    {
        //Many, many cases...
        ...

        default:
            nCkDgt = CalculateCheckDigit(nFormNbr);
            break;
    }

    return nCkDgt;
}

My question is this. Being new-ish to C#, how is GetCheckDigit getting called from a long? What is this syntax?

I don't even know how I would describe/google this!

E Devitt
  • 67
  • 9
  • 1
    GetCheckDigit is basically an extension to long type. You can see it at first parameter. "this long" which means this function can be run on long type. – Magiczne Jan 15 '20 at 21:13

2 Answers2

3

It's an extension method

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

From: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

There's a good example of this on this SO post:

How to extend C# built-in types, like String?

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Kyle
  • 32,731
  • 39
  • 134
  • 184
1

GetCheckDigit is an extension method on the type long

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

Joe H
  • 584
  • 3
  • 14