Results 1 to 23 of 23

Thread: Some explanation about constructor in c#

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2009
    Location
    Watch Window(Shift+f9)
    Posts
    1,879

    Question Some explanation about constructor in c#

    Can anyone tell me ???Why the following code is not working ?let me know some idea.

    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Example9
    {
        class Program
        {
            static void Main(string[] args)
             {
               Public String Program();
               {
                   Console.WriteLine("I am a Constructor");
    
                   return;
               }
                 
            }
        }
    }

  2. #2
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,127

    Re: Some explanation about constructor in c#

    You have a procedure inside a procedure and that is not allowed. Is this a homework of yours?
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  3. #3
    Frenzied Member avrail's Avatar
    Join Date
    Mar 2006
    Location
    Egypt, Cairo
    Posts
    1,221

    Re: Some explanation about constructor in c#

    Quote Originally Posted by firoz.raj View Post
    Can anyone tell me ???Why the following code is not working ?let me know some idea.

    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Example9
    {
        class Program
        {
            static void Main(string[] args)
             {
               Public String Program();
               {
                   Console.WriteLine("I am a Constructor");
    
                   return;
               }
                 
            }
        }
    }
    hay firoz.raj,
    i believe here that you want to create a constructor.
    the constructor must be with the same name of the class, in your case it will be Program.
    you added method definition inside another method, and this is wrong.

    please see this link
    http://www.c-sharpcorner.com/UploadF...sInCSharp.aspx
    You Don't Have to Rate Me.
    I'm Not a Civilized Man I'm the Civilization it self
    White or Black, Living or Dieing and 0 or 1 that's MY life
    iam an Object in Object Oriented Life
    my blog : http://refateid.blogspot.com/
    twitter :@avrail
    010011000111010101110110001000000100110101111001001000000101000001100011

  4. #4

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2009
    Location
    Watch Window(Shift+f9)
    Posts
    1,879

    Question Re: Some explanation about constructor in c#

    Hi Friends,
    Yes i have seen.it is easy to understand.Constructor don't have return type .constructore name is as same as class name.no need to make object of the class of the class.and call to the method of class.using object.but my question is why any need of constructor ???.additional what about copy constructor ,parameterized constructor .Kindly clarify please.
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    
    namespace TestConstructor
    {
        class Program
        {
            static void Main(string[] args)
                   {
                Console.WriteLine("I am the entry point of the Constructor");
                Console.Read();
                Program p = new Program();
                Console.ReadKey();
                            
                    }
            public Program() 
                       {
              Console.WriteLine("I am the default constructor");
                        }
             
        }
    }

  5. #5
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Re: Some explanation about constructor in c#

    I'm not big on the c# vocabulary, so I might be misinterpreting you.

    But if I am correct, I don't think your example is very useful to show the working of parametrized and copy constructors.
    So here's another one:
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace TestConstructor
    {
        class MyCustomClass
        {
            public MyCustomClass() 
            {
              Console.WriteLine("I am the default constructor");
            }
    		
            public MyCustomClass(string Parameter1) 
            {
              Console.WriteLine("I am a copy constructor with the given parameter: " + Parameter1);
            }
    
            public MyCustomClass(int Parameter2) 
            {
              Console.WriteLine("You can make as many copies as you like, though using different types; here's an integer: " + Parameter2);
            }
    		
    		/*public MyCustomClass(string Parameter3) 
            {
              Console.WriteLine("This one would probably not compile because you already have used a string parameter alone.");
            }*/
    		
            public MyCustomClass(string Parameter4, int Parameter5) 
            {
              Console.WriteLine("But this would work again: " + Parameter4 + Parameter5);
            }
        }
    }
    Now when you would type:
    Code:
    MyCustomClass = new MyCustomClass(
    You would get a list of overloads (copy constructors?) showing the different parameter combinations.
    The use of this is that you can initialize your custom classes with dynamic values.

    Hope this helps.
    Delete it. They just clutter threads anyway.

  6. #6
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Re: Some explanation about constructor in c#

    Also VBWire is showing an article that might interest you.
    http://www.informit.com/articles/art...ay&WT.rss_ev=a
    Delete it. They just clutter threads anyway.

  7. #7

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2009
    Location
    Watch Window(Shift+f9)
    Posts
    1,879

    Question Re: Some explanation about constructor in c#

    Can you tell me ? why Console.WriteLine("I am the default constructor") is not printing??? .let me know please.as i know . it is a destructor.but what is the uses of destructor in programme.simple to destroy the resources.let me clarify please.
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    
    namespace TestConstructor
    {
        class Program
        {
            static void Main(string[] args)
                   {
                Console.WriteLine("I am the entry point of the Constructor");
                Console.Read();
                Program p = new Program();
                Console.ReadKey();
                            
                    }
           ~Program() 
                       {
              Console.WriteLine("I am the default constructor");
                        }
             
        }
    }

  8. #8
    Frenzied Member avrail's Avatar
    Join Date
    Mar 2006
    Location
    Egypt, Cairo
    Posts
    1,221

    Re: Some explanation about constructor in c#

    actually i tested this code
    and it printing I am the default constructor
    You Don't Have to Rate Me.
    I'm Not a Civilized Man I'm the Civilization it self
    White or Black, Living or Dieing and 0 or 1 that's MY life
    iam an Object in Object Oriented Life
    my blog : http://refateid.blogspot.com/
    twitter :@avrail
    010011000111010101110110001000000100110101111001001000000101000001100011

  9. #9

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2009
    Location
    Watch Window(Shift+f9)
    Posts
    1,879

    Smile Re: Some explanation about constructor in c#

    How it can be printed ???I am the default constructor .it is a Destructor.it is impossible when you will put ~ sign in the constructor.it destroys the value.
    Even Destructors cannot be overloaded using Function overloading.it called automatically.i want to know the difference between dispose and destructor.
    that is why i posted overhere.
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    
    namespace TestConstructor
    {
        class Program
        {
            static void Main(string[] args)
                   {
                
                Console.WriteLine("I am the entry point of the Constructor");
                Console.Read();
                Program p = new Program();
                Console.ReadKey();
                            
                    }
           ~Program() 
                       {
              Console.WriteLine("I am the default constructor");
                        }
             
        }
    }

  10. #10
    PowerPoster abhijit's Avatar
    Join Date
    Jun 1999
    Location
    Chit Chat Forum.
    Posts
    3,228

    Re: Some explanation about constructor in c#

    Firoz,
    What are you trying to say? I am puzzled by your statement "How can it be printed?"
    Everything that has a computer in will fail. Everything in your life, from a watch to a car to, you know, a radio, to an iPhone, it will fail if it has a computer in it. They should kill the people who made those things.- 'Woz'
    save a blobFileStreamDataTable To Text Filemy blog

  11. #11
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Some explanation about constructor in c#

    I'll admit I'm not 100% up on C#... but if I remember right, the ~ denotes the DESTRUCTOR.... which will run when you set your reference to NILL. It's the opposite of the constructor. Dispose on the other hand is a method that comes from the IDispose interface. If you implement the IDispose interface, then you end up with an additional method Dispose. What's the difference? Dispose give you a little more fine control, and is the appropriate way to properly ensure that any components used by your object is properly cleaned up, such as unmanaged resources.

    The reason for this is noted in the MSDN entry for IDispose
    http://msdn.microsoft.com/en-us/libr...isposable.aspx

    Quote Originally Posted by MSDN
    The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

    Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.
    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  12. #12

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2009
    Location
    Watch Window(Shift+f9)
    Posts
    1,879

    Smile Re: Some explanation about constructor in c#

    Firoz,
    What are you trying to say? I am puzzled by your statement "How can it be printed?"
    this ("I am the default constructor"); message cannot be printed.in the following code.
    Code:
     ~Program() 
                       {
              Console.WriteLine("I am the default constructor");
                        }
    Last edited by firoz.raj; Jul 20th, 2010 at 08:08 AM.

  13. #13
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Re: Some explanation about constructor in c#

    Well if the ~ defines the destructor, you can't see it, no.
    The destructor is fired when the application terminates.
    Only when you'd run the application from the command line it would be visible.
    Delete it. They just clutter threads anyway.

  14. #14
    PowerPoster abhijit's Avatar
    Join Date
    Jun 1999
    Location
    Chit Chat Forum.
    Posts
    3,228

    Re: Some explanation about constructor in c#

    Quote Originally Posted by TheBigB View Post
    Well if the ~ defines the destructor, you can't see it, no.
    The destructor is fired when the application terminates.
    Only when you'd run the application from the command line it would be visible.
    That is correct.
    If you want to check if the destructor is getting fired, add
    Console.Readkey() after the Console.WriteLine

    That will halt program execution.
    Everything that has a computer in will fail. Everything in your life, from a watch to a car to, you know, a radio, to an iPhone, it will fail if it has a computer in it. They should kill the people who made those things.- 'Woz'
    save a blobFileStreamDataTable To Text Filemy blog

  15. #15

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2009
    Location
    Watch Window(Shift+f9)
    Posts
    1,879

    Question Re: Some explanation about constructor in c#

    That is correct.
    If you want to check if the destructor is getting fired, add
    Console.Readkey() after the Console.WriteLine
    Yes really Destructor is getting fired.but i would also like to discuss.Destructor is also prevent Memory leak.Can you tell me some comment????.how it is prevent memory leak???.let me know please.
    Code:
    That will halt program execution. using System;
    using System.Collections.Generic;
    using System.Text;
    
    
    namespace TestConstructor
    {
        class Program
        {
            static void Main(string[] args)
                   {
                
                Console.WriteLine("I am the entry point of the Constructor");
                Console.Read();
                Program p = new Program();
                Console.ReadKey();
                            
                    }
            ~Program()
                  {
                Console.WriteLine("....Cleaning Garbage to prevent Memory Leak");
                Console.ReadKey();
                  }
                 
             
        }
    }

  16. #16
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Some explanation about constructor in c#

    It is used to allow you to clean up any objects you used. As I noted in my post the donstructor is the OPPOSITE of the constructor. Used for destroying the object.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  17. #17

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2009
    Location
    Watch Window(Shift+f9)
    Posts
    1,879

    Question Re: Some explanation about constructor in c#

    It is used to allow you to clean up any objects you used. As I noted in my post the donstructor is the OPPOSITE of the constructor. Used for destroying the object.
    in the following example.how should i clean the form object??? .let me know please.
    Code:
     private void button1_Click(object sender, EventArgs e)
            {
                Form frm = new Form();
                 frm.ShowDialog();
            }

  18. #18
    New Member
    Join Date
    Jul 2010
    Posts
    2

    Re: Some explanation about constructor in c#

    Quote Originally Posted by firoz.raj View Post
    in the following example.how should i clean the form object??? .let me know please.
    Code:
     private void button1_Click(object sender, EventArgs e)
            {
                Form frm = new Form();
                 frm.ShowDialog();
            }
    The frm object will be cleaned up as soon as there are no references remaining to it.

    In this instance, as soon as the button1_Click function completes. This is because ShowDialog opens the form as a modal form, and the method waits for it to return before exiting.

  19. #19
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Some explanation about constructor in c#

    In short, you don't need to (for reasons explained in post #18)...

    And it doesn't matter in the first place as it has nothing to do with the previous conversation regarding the constructor and deconstructor. You're trying to take the concept of one thing and apply it to something completely unrelated.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  20. #20

    Thread Starter
    Frenzied Member
    Join Date
    Jan 2009
    Location
    Watch Window(Shift+f9)
    Posts
    1,879

    Question Re: Some explanation about constructor in c#

    The frm object will be cleaned up as soon as there are no references remaining to it.

    In this instance, as soon as the button1_Click function completes. This is because ShowDialog opens the form as a modal form, and the method waits for it to return before exiting.
    i have seen constructor is very much similar to procedure.constructor don't return value.but procedure returns void.procedure is also used to initialize a variable or object .as per programmer needs.only strong difference i have seen between constructor and procedure.constructor has same name as class name.additionl i still have some doubt regarding copy
    Constructor andparameterized constructior.
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Example3
    {
        class semester
        {
            private int Duration;
            public semester()
            {
                Duration = 144;
            }
            public semester(int d)
            {
                Duration = d;
            }
            public void setDuration(int newDuration)
            {
                Duration = newDuration;
            }
    
            public static void Main()
            {
                semester java = new semester();
                semester csharp = new semester(400);  //here why it is not printing 400.
            }
        }
    }
    Last edited by firoz.raj; Jul 22nd, 2010 at 05:03 AM.

  21. #21
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Some explanation about constructor in c#

    Why would it print? There isn't any code there that outputs anything.

    But yes, the default constructor can be used to set default values for the class. And yes, you can have a parameterized constructor to pass in values to the class.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  22. #22
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Re: Some explanation about constructor in c#

    What techgnome said.
    And take a look at post #5...
    Delete it. They just clutter threads anyway.

  23. #23
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Some explanation about constructor in c#

    Quote Originally Posted by Powerlord View Post
    The frm object will be cleaned up as soon as there are no references remaining to it.

    In this instance, as soon as the button1_Click function completes. This is because ShowDialog opens the form as a modal form, and the method waits for it to return before exiting.
    That is not correct. Objects are not cleaned up when there are no references left to them. When there are no references left to an object it BECOMES ELIGIBLE for garbage collection. When the object actually gets cleaned up is indeterminate, i.e. the system will do it when it's good and ready.

    It's also important to note that object disposal and garbage collection are related but they are NOT the same thing. Disposal is the act of releasing managed and unmanaged resources, while garbage collection is the act of reclaiming the memory occupied by an object. Before an object can be garbage collected it must be disposed. If you don't dispose your own objects yourself then their resources will remain unavailable to the system until it gets around to garbage collecting the object, which may not be until your app closes. It's for this reason that you must ALWAYS explicitly dispose any object that supports it that you create yourself. In this case, closing a form that was displayed using ShowDialog doesn't automaticlly dispose like using Show does. For that reason you MUST dispose the form yourself as soon as you are finished with it. The most appropriate code in this case would be:
    csharp Code:
    1. using (var frm = new Form())
    2. {
    3.     frm.ShowDialog();
    4. }
    The object created at the start of the 'using' block is automatically disposed at the end of the 'using' block. That code is functionally equivalent to:
    csharp Code:
    1. var frm = new Form();
    2.  
    3. try
    4. {
    5.     frm.ShowDialog();
    6. }
    7. finally
    8. {
    9.     frm.Dispose();
    10. }
    Note that a 'using' block includes and implicit try..finally to ensure that the object is disposed even if an exception is thrown, handled or not.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width