Results 1 to 3 of 3

Thread: [RESOLVED] overload constructors

  1. #1

    Thread Starter
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Resolved [RESOLVED] overload constructors

    in C#, how do you call a classes constructor from an overloaded constructor?

    For example.

    Code:
    public class Test
    {
    	private string _arg1 = string.Empty;
    	private string _arg2 = string.Empty;
    
    	public Test(string Arg1)
    	{
    		_arg1 = Arg1;
    	}
    	public Test(string Arg1, string Arg2)
    	{
    		Test(Arg1);
    		_arg2 = Arg2;
    	}
    }
    In VB.NET, since you use call the constructor sub "New" you can have many New subs as long as it obeys overloading rules. Then you can call the first constructor from within the second one.. to cut down on duplicate coding...

    how would I do this in C#? I am sure its just a syntax thing that I am not familiar with.

  2. #2

    Thread Starter
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: overload constructors

    I figured it out by searching around. This would be the proper way (incase anyone else runs into this)

    Code:
    public class Test
    {
    	private string _arg1 = string.Empty;
    	private string _arg2 = string.Empty;
    
    	public Test(string Arg1)
    	{
    		_arg1 = Arg1;
    	}
    	public Test(string Arg1, string Arg2):this(Arg1)
        {
    		_arg2 = Arg2;
    	}
    }

  3. #3
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: [RESOLVED] overload constructors

    Yes. Also if you wanted to call the constructor that was defined ina BASE class then you'd use

    Code:
    public Test(string Arg1, string Arg2):base(Arg1)
    {
    		_arg2 = Arg2;
    }
    I don't live here any more.

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