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. Object creation at internal condition in constructor

Object creation at internal condition in constructor

Scheduled Pinned Locked Moved C#
helptutorialquestion
20 Posts 6 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.
  • T Tony Lambert

    Hi All, I'm having an issue with constructors. I want to prevent the creation internally in the following example: using System; public class ConditionalObject { private string _MajorName; private string _MinorName; public string MajorName { get { return _MajorName; } } public string MinorName { get { return _MinorName; } } public ConditionalObject() { if ((_MajorName.Length == 0) || (_MinorName.Length == 0)) { throw new Exception("Unable to initialise new object without identifier."); /******* what to do here to be destroyed? *******/ } } public ConditionalObject(string AMajorName, string AMinorName): base() { _MajorName = AMajorName; _MinorName = AMinorName; } } Neither Dispose(); nor return null; nor this = null; can be applied in constructor. Could anybody help me guys? Thanks for the answers. :)

    E Offline
    E Offline
    ejuanpp
    wrote on last edited by
    #5

    Why don't you use the factory pattern :)

    T 1 Reply Last reply
    0
    • T Tony Lambert

      Thanks Guffa. Unfortunatelly this is the main problem: it returns the (not null) object reference whatever I've thrown exception or not. :( It is a quite big problem because I couldn't even check the previously unidentified object in the next line externally. Is there any other way to solve this?

      G Offline
      G Offline
      Guffa
      wrote on last edited by
      #6

      Tony Lambert wrote:

      Unfortunatelly this is the main problem: it returns the (not null) object reference whatever I've thrown exception or not.

      So you just catch the exception and ignore it, or what?

      --- It's amazing to see how much work some people will go through just to avoid a little bit of work.

      T 1 Reply Last reply
      0
      • E ejuanpp

        Why don't you use the factory pattern :)

        T Offline
        T Offline
        Tony Lambert
        wrote on last edited by
        #7

        Thanks ejuanpp. Not a bad idea, but I'll be in the same problem: end-developers need to handle it externally or do some kind of validation afterwards and the API will not be consistent. :( I'd like to avoid to leave the default object creation way or do anything "non-standard" to make easier other developers life. :)

        1 Reply Last reply
        0
        • G Guffa

          Tony Lambert wrote:

          Unfortunatelly this is the main problem: it returns the (not null) object reference whatever I've thrown exception or not.

          So you just catch the exception and ignore it, or what?

          --- It's amazing to see how much work some people will go through just to avoid a little bit of work.

          T Offline
          T Offline
          Tony Lambert
          wrote on last edited by
          #8

          I do nothing with it. (should I? :doh:) I just throw it, it raises the exception message and the constructor returns with the object reference in the caller method instead of null. Actually, this is the missing part of the puzzle: how to destroy or give null operand to the object in its constructor or mark it as destroyable or return with null? :(

          G 1 Reply Last reply
          0
          • L Luc Pattyn

            Hi, within your class you could provide a public static method that first checks whatever needs checking, then creates and returns a new instance of your class. Something like:

            public static ConditionalObject Create(int parm) {
            if (parm is OK) {
            return new ConditionalObject(parm);
            } else {
            // one of these could do:
            return null;
            return aDefaultConditionalObject;
            throw new ApplicationException(...);
            }
            }

            The calling code must deal with null or exception of course. :)

            Luc Pattyn

            T Offline
            T Offline
            Tony Lambert
            wrote on last edited by
            #9

            Thanks Luc. I wait for a while than I'll try to solve it this way. :)

            1 Reply Last reply
            0
            • T Tony Lambert

              I do nothing with it. (should I? :doh:) I just throw it, it raises the exception message and the constructor returns with the object reference in the caller method instead of null. Actually, this is the missing part of the puzzle: how to destroy or give null operand to the object in its constructor or mark it as destroyable or return with null? :(

              G Offline
              G Offline
              Guffa
              wrote on last edited by
              #10

              Tony Lambert wrote:

              I just throw it, it raises the exception message and the constructor returns with the object reference in the caller method instead of null.

              No, it doesn't. If you throw an exception in the constructor, the created object is never used. You don't get a reference to the object, as the reference is not assigned to any variable.

              Tony Lambert wrote:

              Actually, this is the missing part of the puzzle: how to destroy or give null operand to the object in its constructor or mark it as destroyable or return with null?

              You can't do that, and you don't need to, as the reference to the object will never be used. Just make sure that the object is left in a state so that it can be garbage collected.

              --- It's amazing to see how much work some people will go through just to avoid a little bit of work.

              L T 2 Replies Last reply
              0
              • T Tony Lambert

                Hi All, I'm having an issue with constructors. I want to prevent the creation internally in the following example: using System; public class ConditionalObject { private string _MajorName; private string _MinorName; public string MajorName { get { return _MajorName; } } public string MinorName { get { return _MinorName; } } public ConditionalObject() { if ((_MajorName.Length == 0) || (_MinorName.Length == 0)) { throw new Exception("Unable to initialise new object without identifier."); /******* what to do here to be destroyed? *******/ } } public ConditionalObject(string AMajorName, string AMinorName): base() { _MajorName = AMajorName; _MinorName = AMinorName; } } Neither Dispose(); nor return null; nor this = null; can be applied in constructor. Could anybody help me guys? Thanks for the answers. :)

                K Offline
                K Offline
                Karthik Kalyanasundaram
                wrote on last edited by
                #11

                I don't know what ur actual intention is, If your intention is to prevent object creation using default constructor aking ur Default Constructor private will solve ur issue.

                1 Reply Last reply
                0
                • G Guffa

                  Tony Lambert wrote:

                  I just throw it, it raises the exception message and the constructor returns with the object reference in the caller method instead of null.

                  No, it doesn't. If you throw an exception in the constructor, the created object is never used. You don't get a reference to the object, as the reference is not assigned to any variable.

                  Tony Lambert wrote:

                  Actually, this is the missing part of the puzzle: how to destroy or give null operand to the object in its constructor or mark it as destroyable or return with null?

                  You can't do that, and you don't need to, as the reference to the object will never be used. Just make sure that the object is left in a state so that it can be garbage collected.

                  --- It's amazing to see how much work some people will go through just to avoid a little bit of work.

                  L Offline
                  L Offline
                  Larantz
                  wrote on last edited by
                  #12

                  I fail to see the use for a constructor that is not sufficient for instanciating your object. Why have the constructor there if it will make an object you deem invalid? Remove it and only accept calls to constructors that initialize the fields you need set. -Larantz-

                  for those about to code, we salute you
                  http://www.tellus-software.com

                  T 1 Reply Last reply
                  0
                  • L Larantz

                    I fail to see the use for a constructor that is not sufficient for instanciating your object. Why have the constructor there if it will make an object you deem invalid? Remove it and only accept calls to constructors that initialize the fields you need set. -Larantz-

                    for those about to code, we salute you
                    http://www.tellus-software.com

                    T Offline
                    T Offline
                    Tony Lambert
                    wrote on last edited by
                    #13

                    "Remove it and only accept calls to constructors that initialize the fields you need set." Well it is okay in end user application, but it's an abstract class in library. Since it will be called by end-developers, the API must be consistent and any internal operation must to be transparent to make the library clear, and understandable.

                    L 1 Reply Last reply
                    0
                    • G Guffa

                      Tony Lambert wrote:

                      I just throw it, it raises the exception message and the constructor returns with the object reference in the caller method instead of null.

                      No, it doesn't. If you throw an exception in the constructor, the created object is never used. You don't get a reference to the object, as the reference is not assigned to any variable.

                      Tony Lambert wrote:

                      Actually, this is the missing part of the puzzle: how to destroy or give null operand to the object in its constructor or mark it as destroyable or return with null?

                      You can't do that, and you don't need to, as the reference to the object will never be used. Just make sure that the object is left in a state so that it can be garbage collected.

                      --- It's amazing to see how much work some people will go through just to avoid a little bit of work.

                      T Offline
                      T Offline
                      Tony Lambert
                      wrote on last edited by
                      #14

                      Thanks again. Here is a simple code: using System; public class ConditionalObject { public ConditionalObject(string name) { try { if (name.Equals("")) { throw new ArgumentOutOfRangeException(this.ToString() + ": Unable to create new object without identifier."); } } catch (ArgumentOutOfRangeException AException) { Console.WriteLine(AException.Message); } } } public class CallerClass { public static void Main() { ConditionalObject obj = new ConditionalObject(""); Console.WriteLine(obj == null ? "null" : "not null"); } } When I change this: ConditionalObject obj = new ConditionalObject(""); to this: ConditionalObject obj = new ConditionalObject("anything"); the last line gives the same value (not null). What did I wrong? :doh:

                      G 1 Reply Last reply
                      0
                      • T Tony Lambert

                        Thanks again. Here is a simple code: using System; public class ConditionalObject { public ConditionalObject(string name) { try { if (name.Equals("")) { throw new ArgumentOutOfRangeException(this.ToString() + ": Unable to create new object without identifier."); } } catch (ArgumentOutOfRangeException AException) { Console.WriteLine(AException.Message); } } } public class CallerClass { public static void Main() { ConditionalObject obj = new ConditionalObject(""); Console.WriteLine(obj == null ? "null" : "not null"); } } When I change this: ConditionalObject obj = new ConditionalObject(""); to this: ConditionalObject obj = new ConditionalObject("anything"); the last line gives the same value (not null). What did I wrong? :doh:

                        G Offline
                        G Offline
                        Guffa
                        wrote on last edited by
                        #15

                        Because you catch the exception inside the constructor, the constructor never exits with an exception.

                        --- It's amazing to see how much work some people will go through just to avoid a little bit of work.

                        T 1 Reply Last reply
                        0
                        • G Guffa

                          Because you catch the exception inside the constructor, the constructor never exits with an exception.

                          --- It's amazing to see how much work some people will go through just to avoid a little bit of work.

                          T Offline
                          T Offline
                          Tony Lambert
                          wrote on last edited by
                          #16

                          It is the same without catch (first example). When I throw an exception it only gets registered in an exception buffer till something catches. It does nothing with the constructor itself. That is the reason why it comes back with not null value all the time. :( When I don't catch it, the application gets killed at the exit point of constuctor. That's another problem: I need that null value. :( Anyway, somebody has given to me another solution with indirect static method initialisation in the next thread. I think I'll do it that way. :doh: Thanks to All again. :)

                          G 1 Reply Last reply
                          0
                          • T Tony Lambert

                            It is the same without catch (first example). When I throw an exception it only gets registered in an exception buffer till something catches. It does nothing with the constructor itself. That is the reason why it comes back with not null value all the time. :( When I don't catch it, the application gets killed at the exit point of constuctor. That's another problem: I need that null value. :( Anyway, somebody has given to me another solution with indirect static method initialisation in the next thread. I think I'll do it that way. :doh: Thanks to All again. :)

                            G Offline
                            G Offline
                            Guffa
                            wrote on last edited by
                            #17

                            Tony Lambert wrote:

                            It is the same without catch (first example). When I throw an exception it only gets registered in an exception buffer till something catches. It does nothing with the constructor itself. That is the reason why it comes back with not null value all the time.

                            An exception buffer? Why do you think that? When you throw an exception in the constructor it immediately exits. The exception isn't stored in any buffer anywhere, it's returned from the constructor.

                            Tony Lambert wrote:

                            When I don't catch it, the application gets killed at the exit point of constuctor.

                            No, the application doesn't get killed. The constructor exits with an exception, and the exception travels through each level in the call stack until it's caught somewhere. As you don't catch it in your program, the program exits with the exception and it's caught by the system.

                            Tony Lambert wrote:

                            That's another problem: I need that null value.

                            A constructor never returns a null value, it always returns the address of the object. If you wan't to abort a constructor, an exception is the only way to do that, and you have to catch the exception in the code that calls the constructor for it to be useful.

                            --- It's amazing to see how much work some people will go through just to avoid a little bit of work.

                            T 1 Reply Last reply
                            0
                            • T Tony Lambert

                              "Remove it and only accept calls to constructors that initialize the fields you need set." Well it is okay in end user application, but it's an abstract class in library. Since it will be called by end-developers, the API must be consistent and any internal operation must to be transparent to make the library clear, and understandable.

                              L Offline
                              L Offline
                              Larantz
                              wrote on last edited by
                              #18

                              Quote:

                              public class ConditionalObject
                              {
                                 public ConditionalObject(string name)
                                 {
                                    try
                                    {
                                       if (name.Equals(""))
                                       {
                                          throw new ArgumentOutOfRangeException(this.ToString() +
                                          ": Unable to create new object without identifier.");
                                       }
                                    }
                                    catch (ArgumentOutOfRangeException AException)
                                    {
                                       Console.WriteLine(AException.Message);
                                    }
                                 }
                              }
                              

                              Your next example was according to what I meant. No empty constructors :) -Larantz-

                              for those about to code, we salute you
                              http://www.tellus-software.com

                              T 1 Reply Last reply
                              0
                              • G Guffa

                                Tony Lambert wrote:

                                It is the same without catch (first example). When I throw an exception it only gets registered in an exception buffer till something catches. It does nothing with the constructor itself. That is the reason why it comes back with not null value all the time.

                                An exception buffer? Why do you think that? When you throw an exception in the constructor it immediately exits. The exception isn't stored in any buffer anywhere, it's returned from the constructor.

                                Tony Lambert wrote:

                                When I don't catch it, the application gets killed at the exit point of constuctor.

                                No, the application doesn't get killed. The constructor exits with an exception, and the exception travels through each level in the call stack until it's caught somewhere. As you don't catch it in your program, the program exits with the exception and it's caught by the system.

                                Tony Lambert wrote:

                                That's another problem: I need that null value.

                                A constructor never returns a null value, it always returns the address of the object. If you wan't to abort a constructor, an exception is the only way to do that, and you have to catch the exception in the code that calls the constructor for it to be useful.

                                --- It's amazing to see how much work some people will go through just to avoid a little bit of work.

                                T Offline
                                T Offline
                                Tony Lambert
                                wrote on last edited by
                                #19

                                "An exception buffer? Why do you think that?" call stack :) Thanks Guffa. I think you're right, it comes back with object reference. BTW, I've solved this issue across a static init method, where I do the try/cacth as well before the instance gets created. The constructor is hidden now. :-)

                                1 Reply Last reply
                                0
                                • L Larantz

                                  Quote:

                                  public class ConditionalObject
                                  {
                                     public ConditionalObject(string name)
                                     {
                                        try
                                        {
                                           if (name.Equals(""))
                                           {
                                              throw new ArgumentOutOfRangeException(this.ToString() +
                                              ": Unable to create new object without identifier.");
                                           }
                                        }
                                        catch (ArgumentOutOfRangeException AException)
                                        {
                                           Console.WriteLine(AException.Message);
                                        }
                                     }
                                  }
                                  

                                  Your next example was according to what I meant. No empty constructors :) -Larantz-

                                  for those about to code, we salute you
                                  http://www.tellus-software.com

                                  T Offline
                                  T Offline
                                  Tony Lambert
                                  wrote on last edited by
                                  #20

                                  :)

                                  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