Reputation: 829
Lets say I have this class called class1, class1 contains one default constructor and one that takes one parameter (say a string for example). Inside that constructor I set up a variable, lets call it "string var". I want var to get the value from the string that I passed to the constructor while creating that object, but I want to be able to use var outside of the constructors scope, is that possible? since constructors doesen't return values and whatnot.
To clarify here is a code example of what I want to do:
class class1
{
public class1(string songPath)
{
System.Media.SoundPlayer songPlayer = new System.Media.SoundPlayer(songPath);
}
//here I want to use my songPlayer I created with the passed string as songPath
}
Upvotes: 2
Views: 71
Reputation: 176886
just create property like this
//System.Media.SoundPlayer _songPlayer ;
public System.Media.SoundPlayer songPlayer
{
//if you have nay logic to handle ull
//get{ if(_songPlayer != null) return _songPlayer; else null; } or just
get;
}
public class1(string songPath)
{
SongPlayer = new System.Media.SoundPlayer(songPath);
//_songPlayer = new System.Media.SoundPlayer(songPath);
}
Note : helpful if you want to use this member outside class otherwise its better to go with @Oded solution..
And use private vriable for property if you want to handle null situation
Upvotes: 1
Reputation: 22334
Another option for you might be a static class and method
public static class1(string songPath)
{
public static System.Media.SoundPlayer play(string songPath)
{
System.Media.SoundPlayer songPlayer = new System.Media.SoundPlayer(songPath);
// play here ?
// or return to play
return songPLayer;
}
}
Upvotes: 1
Reputation: 498904
You need to make songPlayer
a field - it is a local variable only visible to the constructor it is declared in at the moment.
private System.Media.SoundPlayer songPlayer;
public class1(string songPath)
{
songPlayer = new System.Media.SoundPlayer(songPath);
}
Upvotes: 4