Solved

How can I use the constructor value of Class? out of the class?

Posted on 2014-10-30
16
207 Views
Last Modified: 2014-10-31
Hi there,

I have a class and I am initializing the values in the constructor as
  public DBHelper(sstring logopath )
        {
            this.PackagePath = plogopath;
}

Open in new window


Is there any way I can use this value out of class?
I am drawing the file in another class.
Thanks.
0
Comment
Question by:developer2012
  • 7
  • 6
  • 2
  • +1
16 Comments
 
LVL 14

Expert Comment

by:Tchuki
ID: 40414729
You can expose the value as a public property, for example:

public class DBHelper
{
  public DBHelper(string logPath)
  {
    this.PackagePath = logPath;
  }

  public string PackagePath { get; private set; }
}

public class SomeOtherClass
{
  // create dbhelper class and set the path
  private DBHelper dbHelper = new DBHelper("path");
  // return the path from dbhelper
  var logPath = dbHelper.PackagePath;
}

Open in new window

0
 
LVL 33

Expert Comment

by:Mike Eghtebas
ID: 40414950
When you are initializing a class, you must have been doing something like:

(if DBHelper is your class name)

DBHelper db_help = new DBHelper(

As you key (, you will see how many constructors this class has (that is if you are working in an environment like visual studio). Often the options are:

- no argument to be supplied,
- one or more arguments to be supplied.

Often, there are 3 or 4 constructors depending on the class designed.

Unless you have the class and post here, one cannot tell the possibilities there are to initialize your db_help object.  

Mike
0
 

Author Comment

by:developer2012
ID: 40415827
Thanks for the response but I know how to initialize the class with a constructor.

To be more  clear, I have a value in a constructor

For example I already got the value of plogopath = "C:/"

So my question is can I use send the same  value to other class by any means?

Thanks.
0
 
LVL 32

Assisted Solution

by:it_saige
it_saige earned 500 total points
ID: 40415904
As Tchuki said, expose it as a public property.
public class DBHelper
{
	public DBHelper(string logPath)
	{
		PackagePath = logPath;
	}

	// Private set just signifies that only this class can modify the underlying value.
	public string PackagePath { get; private set; }
}

public class SomeOtherClass
{
	// create dbhelper class and set the path
	private DBHelper dbHelper = new DBHelper("path");
	// return the path from dbhelper
	var logPath = dbHelper.PackagePath;
}

Open in new window


Now if you need to modify the value of the path from another class then DBHelper would be defined as such:
public class DBHelper
{
	public DBHelper(string logPath)
	{
		PackagePath = logPath;
	}

	// Now anyone can modify me.
	public string PackagePath { get; set; }
}

Open in new window


And if you wanted to get explicit with your definition of PackagePath:
public class DBHelper
{
	private string _packagePath = string.Empty;

	public DBHelper(string logPath)
	{
		PackagePath = logPath;
	}

	// Anyone can modify me, i've just explicitly defined a backing store.
	public string PackagePath
	{ 
		get { return _packagePath; } 
		set
		{
			if (!value.Equals(_packagePath))
				_packagePath = value;
		} 
	}
}

Open in new window


-saige-
0
 
LVL 32

Expert Comment

by:it_saige
ID: 40415918
Or are you talking about initializing properties in the class from the constructor call like this:
private DBHelper dbHelper = new DBHelper() { PackagePath = "path" };

Open in new window


If thats the case, then all we have to do is define an empty constructor as your class does not have one:
public class DBHelper
{
	public DBHelper() { ;}

	public DBHelper(string logPath)
	{
		PackagePath = logPath;
	}

	// Now anyone can modify me.
	public string PackagePath { get; set; }
}

Open in new window


-saige-
0
 

Author Comment

by:developer2012
ID: 40415928
Saige,

Thanks for the detailed answer.   I declared an empty constructor and tried to access the PackagePath.  

   DBHelper pd = newDBHelper("");
             var logpath = pd.PackageLogoPath;

Open in new window


It reutrns me nothing.  It returns me an empty string.

Thanks.
0
 
LVL 32

Expert Comment

by:it_saige
ID: 40415946
Thats because you passed it nothing.  You passed an empty string.
using System;

public class Program
{
	public class DBHelper
	{
		public string PackagePath { get; set; }

		public DBHelper() { ;}
		public DBHelper(string Path)
		{
			PackagePath = Path;
		}
	}

	public static void Main()
	{
		DBHelper helper = new DBHelper("This is my path");
		Console.WriteLine(helper.PackagePath);
		helper = new DBHelper() { PackagePath = "Now we are just getting fancy" };
		Console.WriteLine(helper.PackagePath);
		Console.ReadLine();
	}
}

Open in new window


Produces the following output:Capture.JPG
-saige-
0
 

Author Comment

by:developer2012
ID: 40415947
Can not I just use the value which I am initializing in the DBHelper Class.

When I initialized the DBHelper class with constructor, the value of logpath = "C:\Documents\Bitmap" and I want to use the same path for my other class and I am unable to do so.  
Is it possible?

Thanks.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 32

Expert Comment

by:it_saige
ID: 40415950
What other class?  What error are you receiving?

-saige-
0
 
LVL 32

Expert Comment

by:it_saige
ID: 40415972
Just assuming this is what you mean:
using System;

public class Program
{
	public class DBHelper
	{
		public string PackagePath { get; set; }

		public DBHelper() { ;}
		public DBHelper(string Path)
		{
			PackagePath = Path;
		}
	}

	public class SomeOtherClass
	{
		public string Path { get; set; }

		public SomeOtherClass() { ;}

		public SomeOtherClass(string Path)
		{
			this.Path = Path;
		}
	}

	public static void Main()
	{
		// Define helper using the constructor and write the PackagePath to the console.
		DBHelper helper = new DBHelper("This is my path");
		Console.WriteLine(string.Format("The path for DBHelper is - {0}", helper.PackagePath));

		// Define otherClass using the constructor and write the Path to the console.
		SomeOtherClass otherClass = new SomeOtherClass(helper.PackagePath);
		Console.WriteLine(string.Format("The path for SomeOtherClass is - {0}", otherClass.Path));

		// Redefine helper using property initialization and write the PackagePath to the console.
		helper = new DBHelper() { PackagePath = "Now we are just getting fancy" };
		Console.WriteLine(string.Format("The new path for DBHelper is - {0}", helper.PackagePath));

		// Redefine otherClass using property initialization and write the Path to the console.
		otherClass = new SomeOtherClass() { Path = helper.PackagePath };
		Console.WriteLine(string.Format("The new path for SomeOtherClass is - {0}", otherClass.Path));

		// Wait for user input to close the program.
		Console.ReadLine();
	}
}

Open in new window


Produces the following output:Capture.JPG
-saige-
0
 

Author Comment

by:developer2012
ID: 40415978
I have a class where I am drawing the Image and I need to pass this same logo path into that class. And this logo path is being passed tp DbHelper through another class.
0
 
LVL 32

Expert Comment

by:it_saige
ID: 40415979
My above example provides a way.

-saige-
0
 

Author Comment

by:developer2012
ID: 40415986
Thanks Saige, I will have a look at it.
0
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 40416009
I should add, that you don't have to *construct* a class to modify it's properties as long as they are:
1.  Public
2.  Not defined as private set;
3.  Backing store fields are not defined as readonly.

Example -
using System;

public class Program
{
	public class DBHelper
	{
		public string PackagePath { get; set; }

		public DBHelper() { ;}
		public DBHelper(string Path)
		{
			PackagePath = Path;
		}
	}

	public class SomeOtherClass
	{
		public string Path { get; set; }

		public SomeOtherClass() { ;}
		public SomeOtherClass(string Path)
		{
			this.Path = Path;
		}
	}

	public static void Main()
	{
		// Define helper and write the PackagePath to the console.
		DBHelper helper = new DBHelper("This is my path");
		Console.WriteLine(string.Format("The path for DBHelper is - {0}", helper.PackagePath));

		// Define otherClass and write the Path to the console.
		SomeOtherClass otherClass = new SomeOtherClass();
		otherClass.Path = helper.PackagePath;
		Console.WriteLine(string.Format("The path for SomeOtherClass is - {0}", otherClass.Path));

		// Wait for user input to close the program.
		Console.ReadLine();
	}
}

Open in new window


Produces the following output:Capture.JPG
If I take and define SomeOtherClass.Path like -
		public string Path { get; private set; }

Open in new window


Then I receive the following compiler warning:Capture.JPG
And if I define SomeOtherClass.Path as a backing field marked as readonly -
		private readonly string _path;
		public string Path
		{
			get { return _path; }
		}

Open in new window


I get the following compiler warning:Capture.JPG
-saige-
0
 
LVL 14

Expert Comment

by:Tchuki
ID: 40416252
it_saige has provided some great information and without repeating what (s)he has provided, I thought I would add an explanation as to the behaviour you have described.

The behaviour you have described is due to scope.  Whilst your two objects may both have a member called PackagePath, setting this member on one object does not also set it on the other.  Instances of objects encapsulate their own state (amongst other things and ignoring static members for simplicity) even when they are created from the same class, see the following code snippet for an example.

namespace EE.Q_28548118.ConsoleApp
{
    using System;

    internal class Program
    {
        private static void Main()
        {
            // Instantiate a new ClassA object and initialise the PackagePath property via the constructor
            var classA = new ClassA(@"C:\images\pets");
            // What is the PackagePath property value?
            Console.WriteLine("classA PackagePath {0}", classA.PackagePath);

            // Instantiate a new ClassB object
            var classB = new ClassB();
            // What is the PackagePath property value?
            Console.WriteLine("classB PackagePath {0}", classB.PackagePath);

            // Instantiate another new ClassA object but DO NOT initialise the PackagePath property
            var classA2 = new ClassA();
            // What is the PackagePath property value?
            Console.WriteLine("classA2 PackagePath {0}", classA2.PackagePath);

            Console.ReadKey();
        }
    }

    public class ClassA
    {
        public ClassA(string logPath = null)
        {
            this.PackagePath = logPath;
        }

        public string PackagePath { get; set; }
    }

    public class ClassB
    {
        public ClassB(string logPath = null)
        {
            this.PackagePath = logPath;
        }

        public string PackagePath { get; set; }
    }
}

Open in new window


I am assuming from the later comments you have made in this question that you do not want to have to manually provide a value for the string logPath argument of your DBHelper constructor in the form of a magic string (seems sensible to me).  I am also assuming that you would really like to reuse the value of a filed/property in another object which should represent the same logPath value in DBHelper.

You can achieve this either by exposing the field/property on your other object (exposing properties has already been covered in the above comments) and then pass the property into your constructor as an argument, se below for an example.

namespace EE.Q_28548118.ConsoleApp
{
    using System;

    internal class Program
    {
        private static void Main()
        {
            // Instantiate a new ClassA object and initialise the PackagePath property via the constructor
            var classA = new ClassA(@"C:\images\pets");
            // What is the PackagePath property value?
            Console.WriteLine("classA PackagePath {0}", classA.PackagePath);

            // Instantiate a new ClassB object using the PackagePath property of classA as the constructor argument
            var classB = new ClassB(classA.PackagePath);
            // What is the PackagePath property value?
            Console.WriteLine("classB PackagePath {0}", classB.PackagePath);

            Console.ReadKey();
        }
    }
}

Open in new window


Alternatively you could pass the entire object as an argument to DBHelper and then access the exposed property in its constructor body, see below.

namespace EE.Q_28548118.ConsoleApp
{
    using System;

    internal class Program
    {
        private static void Main()
        {
            // Instantiate a new ClassA object and initialise the PackagePath property via the constructor
            var classA = new ClassA(@"C:\images\pets");
            // What is the PackagePath property value?
            Console.WriteLine("classA PackagePath {0}", classA.PackagePath);

            // Instantiate a new ClassB object
            var classB = new ClassB(classA);
            // What is the PackagePath property value?
            Console.WriteLine("classB PackagePath {0}", classB.PackagePath);

            Console.ReadKey();
        }
    }

    public class ClassA
    {
        public ClassA(string logPath = null)
        {
            this.PackagePath = logPath;
        }

        public string PackagePath { get; set; }
    }

    public class ClassB
    {
        public ClassB(ClassA classA)
        {
            this.PackagePath = classA.PackagePath;
        }

        public string PackagePath { get; set; }
    }
}

Open in new window


The above has the same outcome as passing just the property, however, it might be that your DBHelper and other object work closely with one another, in which case passing an object might make sense for your scenario.

Hopefully that adequately explains the behaviour you have described (and makes some sense).
0
 

Author Closing Comment

by:developer2012
ID: 40416533
Thanks It_Seige and Tchuki.  Both of your answers were well documented and explained.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now