I'm slowly learning C# and bit confused about the code. I have here a simplified version of my class for the database connection settings
public class DatabaseSettings
{
private static string connectionString = string.Empty;
public static string ConnectionString
{
get
{
return connectionString;
}
private set
{
connectionString = value;
}
}
public bool TestConnection()
{
bool _returnVal = false;
string _connectionString = String.Format("Data Source={0};Persist Security Info=False", databaseLocation);
using (SqlCeConnection connection = new SqlCeConnection(_connectionString))
{
try
{
connection.Open();
connectionString = _connectionString; // sets the value of the connection string here
_returnVal = true;
}
catch (SqlCeException e)
{
// other codes here
_returnVal = false;
}
finally
{
connection.Close();
}
}
return _returnVal;
}
// other methods here
}
now on my Main Class
, I am confused what is happening here. When i tried this code:
string _databaseLocation = "database path";
DatabaseSettings _dbaseSetting = new DatabaseSettings(_databaseLocation, true);
_dbaseSetting.TestConnection();
string newConnectionString = _dbaseSetting.ConnectionString;
// ^ i got an error here
// Member 'SQLCE_Sample.ClassList.DatabaseSettings.ConnectionString.get'
// cannot be accessed with an instance reference;
// qualify it with a type name instead
this one below works without an error but the problem is I got an empty string:
string _databaseLocation = "database path";
DatabaseSettings _dbaseSetting = new DatabaseSettings(_databaseLocation, true);
string newConnectionString = DatabaseSettings.ConnectionString;
What I really want is I need to create a class that has a public method
which tests the connection from the application to the database . Inside that method contains a syntax that sets the value of the connection string . Then I need also a property
that retrieves the value of the connection string without instantiating the class ( that's why i added the static
keyword ). How can I possibly to this?
It appears you want to access (statically) the value of a property that is set by an instance of your class. So, all you need to do is listen to the compiler error -- access the property as a static reference rather than an instance reference. Change:
string newConnectionString = _dbaseSetting.ConnectionString;
To:
string newConnectionString = DatabaseSettings.ConnectionString;
You'll of course need to make sure that you call TestConnection
on the instance before you ever try to access the propery statically like this; otherwise ConnectionString
will be null.
Your public static variable and static property have same name. Rename either of them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.