Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Ensure a parameter is not null

Ensure a parameter is not null

Scheduled Pinned Locked Moved C#
csharpc++question
14 Posts 9 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Dy

    In C++ I can ensure that objects passed to my function are not null by making them a reference like so:

    void foo(MyObjectType &anObject) { ... }

    Is it possible to do this in C#?

    - Dy

    D Offline
    D Offline
    Dave Sexton
    wrote on last edited by
    #4

    Personally, I'd check for that before I call foo.

    if(myObjectType != null)
    {
    foo(myObjectType);
    }

    But fortunately we have the nanny-state politicians who can step in to protect us poor stupid consumers, most of whom would not know a JVM from a frozen chicken. Bruce Pierson
    Because programming is an art, not a science. Marc Clifton

    V 1 Reply Last reply
    0
    • D Dy

      In C++ I can ensure that objects passed to my function are not null by making them a reference like so:

      void foo(MyObjectType &anObject) { ... }

      Is it possible to do this in C#?

      - Dy

      C Offline
      C Offline
      Christian Graus
      wrote on last edited by
      #5

      There's the ?? operator, I assume it would work when you call a method. But, in C# all classes are references. And, you can pass null through that function anyhow, so you can't do that in C#. You have the ref keyword but it only works on value types. You can put 'ref' on a class param, but it makes no difference, it was a reference to start with

      Christian Graus Please read this if you don't understand the answer I've given you "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

      M S V 3 Replies Last reply
      0
      • C Christian Graus

        There's the ?? operator, I assume it would work when you call a method. But, in C# all classes are references. And, you can pass null through that function anyhow, so you can't do that in C#. You have the ref keyword but it only works on value types. You can put 'ref' on a class param, but it makes no difference, it was a reference to start with

        Christian Graus Please read this if you don't understand the answer I've given you "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

        M Offline
        M Offline
        Malcolm Smart
        wrote on last edited by
        #6

        Christian Graus wrote:

        You have the ref keyword but it only works on value types

        Can you explain? String is a predefined reference type, but when passed as a parameter, it is passed by value. To change the string, you have to explicitly mark it as ref in the signature

        namespace RefChecker
        {
            class Program
            {
                static void changeMyString1(string myString)
                {
                    myString += " worked";
                }
        
                static void changeMyString2(ref string myString)
                {
                    myString += " worked"; 
                }
        
                static void Main(string[] args)
                {
                    string string1 = "has it";
                    string string2 = "has it";
        
                    changeMyString1(string1);
                    changeMyString2(ref string2);
        
                    Console.WriteLine(string1);//outputs has it
                    Console.WriteLine(string2);//outputs has it worked
        
                }
            }
        }
        

        Knowledge is hereditary, it will find its way up or down. Luc Pattyn
        and since what every time when i want to add button to this control one add two times posted in C# forum

        C 1 Reply Last reply
        0
        • D Dy

          In C++ I can ensure that objects passed to my function are not null by making them a reference like so:

          void foo(MyObjectType &anObject) { ... }

          Is it possible to do this in C#?

          - Dy

          P Offline
          P Offline
          PIEBALDconsult
          wrote on last edited by
          #7

          As mentioned, that won't even work in C++. However, this[^] article is my attempt to accomplish that in C#. See the comments for other ideas.

          1 Reply Last reply
          0
          • M Malcolm Smart

            Christian Graus wrote:

            You have the ref keyword but it only works on value types

            Can you explain? String is a predefined reference type, but when passed as a parameter, it is passed by value. To change the string, you have to explicitly mark it as ref in the signature

            namespace RefChecker
            {
                class Program
                {
                    static void changeMyString1(string myString)
                    {
                        myString += " worked";
                    }
            
                    static void changeMyString2(ref string myString)
                    {
                        myString += " worked"; 
                    }
            
                    static void Main(string[] args)
                    {
                        string string1 = "has it";
                        string string2 = "has it";
            
                        changeMyString1(string1);
                        changeMyString2(ref string2);
            
                        Console.WriteLine(string1);//outputs has it
                        Console.WriteLine(string2);//outputs has it worked
            
                    }
                }
            }
            

            Knowledge is hereditary, it will find its way up or down. Luc Pattyn
            and since what every time when i want to add button to this control one add two times posted in C# forum

            C Offline
            C Offline
            Christian Graus
            wrote on last edited by
            #8

            The string class is a special case in a number of ways. Any other class, is passed by ref, always.

            Christian Graus Please read this if you don't understand the answer I've given you "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

            1 Reply Last reply
            0
            • C Christian Graus

              There's the ?? operator, I assume it would work when you call a method. But, in C# all classes are references. And, you can pass null through that function anyhow, so you can't do that in C#. You have the ref keyword but it only works on value types. You can put 'ref' on a class param, but it makes no difference, it was a reference to start with

              Christian Graus Please read this if you don't understand the answer I've given you "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

              S Offline
              S Offline
              S Senthil Kumar
              wrote on last edited by
              #9

              Christian Graus wrote:

              You have the ref keyword but it only works on value types. You can put 'ref' on a class param, but it makes no difference, it was a reference to start with

              No, it does make a difference. If you pass a reference type with "ref", you are essentially passing a reference to the reference (something like a pointer to a pointer in C++). For example.

              class A
              {
              public int x;
              }

              void Method()
              {
              A a = new A();
              M1(ref a);
              Console.WriteLine(a.x); // prints 1

              a = new A();
              M2(a);
              Console.WriteLine(a.x); // prints 0
              }

              void M1(ref A a)
              {
              a = new A();
              a.x = 1;
              }

              void M2(A a)
              {
              a = new A();
              a.x = 2;
              }

              M1 takes a by ref and therefore assigning to a changes the reference itself. M2 takes a by value, so changing a doesn't change the a in Method.

              Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

              V M 2 Replies Last reply
              0
              • D Dave Sexton

                Personally, I'd check for that before I call foo.

                if(myObjectType != null)
                {
                foo(myObjectType);
                }

                But fortunately we have the nanny-state politicians who can step in to protect us poor stupid consumers, most of whom would not know a JVM from a frozen chicken. Bruce Pierson
                Because programming is an art, not a science. Marc Clifton

                V Offline
                V Offline
                Vikram A Punathambekar
                wrote on last edited by
                #10

                Much better to do it inside the function since: 1. You only have to do the check once (of course, the caller has to code defensively). 2. There's a reason NullReferenceException is there.

                Cheers, Vikram.


                The hands that help are holier than the lips that pray.

                1 Reply Last reply
                0
                • S S Senthil Kumar

                  Christian Graus wrote:

                  You have the ref keyword but it only works on value types. You can put 'ref' on a class param, but it makes no difference, it was a reference to start with

                  No, it does make a difference. If you pass a reference type with "ref", you are essentially passing a reference to the reference (something like a pointer to a pointer in C++). For example.

                  class A
                  {
                  public int x;
                  }

                  void Method()
                  {
                  A a = new A();
                  M1(ref a);
                  Console.WriteLine(a.x); // prints 1

                  a = new A();
                  M2(a);
                  Console.WriteLine(a.x); // prints 0
                  }

                  void M1(ref A a)
                  {
                  a = new A();
                  a.x = 1;
                  }

                  void M2(A a)
                  {
                  a = new A();
                  a.x = 2;
                  }

                  M1 takes a by ref and therefore assigning to a changes the reference itself. M2 takes a by value, so changing a doesn't change the a in Method.

                  Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

                  V Offline
                  V Offline
                  Vikram A Punathambekar
                  wrote on last edited by
                  #11

                  :applause: I can't believe how few people know about this. And I'm far from being a guru myself. :sigh:

                  Cheers, Vikram.


                  The hands that help are holier than the lips that pray.

                  1 Reply Last reply
                  0
                  • C Christian Graus

                    There's the ?? operator, I assume it would work when you call a method. But, in C# all classes are references. And, you can pass null through that function anyhow, so you can't do that in C#. You have the ref keyword but it only works on value types. You can put 'ref' on a class param, but it makes no difference, it was a reference to start with

                    Christian Graus Please read this if you don't understand the answer I've given you "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

                    V Offline
                    V Offline
                    Vikram A Punathambekar
                    wrote on last edited by
                    #12

                    Christian Graus wrote:

                    You have the ref keyword but it only works on value types. You can put 'ref' on a class param, but it makes no difference, it was a reference to start with

                    In addition to what Senthil said, it helps to think of it like this: if you pass an object as you would regularly do, it gets passed by reference, but that reference is passed by value; if you pass an object by ref, the reference is passed by reference. That's how my Java friend taught me (it's the same in magical Javaland). It looks like codswallop, but it really works wonders once you get the hang of it.

                    Cheers, Vikram.


                    The hands that help are holier than the lips that pray.

                    1 Reply Last reply
                    0
                    • S S Senthil Kumar

                      Christian Graus wrote:

                      You have the ref keyword but it only works on value types. You can put 'ref' on a class param, but it makes no difference, it was a reference to start with

                      No, it does make a difference. If you pass a reference type with "ref", you are essentially passing a reference to the reference (something like a pointer to a pointer in C++). For example.

                      class A
                      {
                      public int x;
                      }

                      void Method()
                      {
                      A a = new A();
                      M1(ref a);
                      Console.WriteLine(a.x); // prints 1

                      a = new A();
                      M2(a);
                      Console.WriteLine(a.x); // prints 0
                      }

                      void M1(ref A a)
                      {
                      a = new A();
                      a.x = 1;
                      }

                      void M2(A a)
                      {
                      a = new A();
                      a.x = 2;
                      }

                      M1 takes a by ref and therefore assigning to a changes the reference itself. M2 takes a by value, so changing a doesn't change the a in Method.

                      Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

                      M Offline
                      M Offline
                      Malcolm Smart
                      wrote on last edited by
                      #13

                      You are actually assigned a new reference here, not changing the object the reference refers to. Try this...
                      class Program { class MyClass { public int x; } static void changeMyClass1(MyClass myClass ) { myClass.x = 100; } static void changeMyClass2(ref MyClass myClass ) { myClass.x = 100; } static void Main(string[] args) { MyClass instance1 = new MyClass(); MyClass instance2 = new MyClass(); instance1.x = 0; instance2.x = 0; changeMyClass1(instance1); changeMyClass2(ref instance2); Console.WriteLine(instance1.x);//outputs 100 Console.WriteLine(instance2.x);//outputs 100 } }Like CG said, they are by ref, by default. Both instances will change. Strings behave differently, which, in my opinion is bad.

                      Knowledge is hereditary, it will find its way up or down. Luc Pattyn
                      and since what every time when i want to add button to this control one add two times posted in C# forum

                      S 1 Reply Last reply
                      0
                      • M Malcolm Smart

                        You are actually assigned a new reference here, not changing the object the reference refers to. Try this...
                        class Program { class MyClass { public int x; } static void changeMyClass1(MyClass myClass ) { myClass.x = 100; } static void changeMyClass2(ref MyClass myClass ) { myClass.x = 100; } static void Main(string[] args) { MyClass instance1 = new MyClass(); MyClass instance2 = new MyClass(); instance1.x = 0; instance2.x = 0; changeMyClass1(instance1); changeMyClass2(ref instance2); Console.WriteLine(instance1.x);//outputs 100 Console.WriteLine(instance2.x);//outputs 100 } }Like CG said, they are by ref, by default. Both instances will change. Strings behave differently, which, in my opinion is bad.

                        Knowledge is hereditary, it will find its way up or down. Luc Pattyn
                        and since what every time when i want to add button to this control one add two times posted in C# forum

                        S Offline
                        S Offline
                        S Senthil Kumar
                        wrote on last edited by
                        #14

                        Malcolm Smart wrote:

                        Like CG said, they are by ref, by default. Both instances will change.

                        Yes, but as you pointed out, passing the parameter with "ref" allows you to change the reference itself - which is different from changing the object being referenced. In your example, both methods only change the object being referenced, and there is no difference in that case. My point was passing reference types for "ref" has a different meaning than passing them without "ref". And strings don't behave differently - strings are immutable reference types. In your example,

                        static void changeMyString1(string myString)
                        {
                        myString = mystring + " worked";
                        }

                            static void changeMyString2(ref string myString)
                            {
                                myString = mystring + " worked"; 
                            }
                        

                        the second method takes myString by ref, and therefore changes the reference itself. After both methods have executed, mystring will be referring to a new string object with " worked" concatentated. By passing myString as ref in the second method, the "original" myString that was passed to changeMyString2 changes to refer to the new string object. The first method doesn't take myString by ref, and therefore the original myString passed doesn't change. If you know C++, the following piece of code demonstrates the difference.

                        int global = 10;

                        void Test()
                        {
                        int val = 0;

                        int *p = &val;
                        Method2(p); // *p = 0;
                        Method1(&p); // *p = 10
                        }

                        void Method1(int **p)
                        {
                        *p = &g;
                        }

                        void Method2(int *p)
                        {
                        p = &g;
                        }

                        You can consider p to be equivalent to a reference type. Method2 is equivalent to not passing with "ref", and Method1 is equivalent to passing with "ref". Changing p inside Method2 doesn't affect p in Test, but changing *p in Method1 does.

                        Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups