Somebody
Somebody

Reputation: 2779

using variables from another file .cs

I have a project in c# winforms, with a file called: PublicSettings.cs (this file is within a folder called: Class) where I have a variable.

Now, I want to use that variable from another file within the same project.

PublicSettings.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LVSetup.Class
{
    class PublicSettings
    {        
        private string _ConnStr = "Connection";

        public string ConnStr
        {
            get
            {
                return this._ConnStr;
            }
            set
            {
                this._ConnStr = value;
            }
        }
    }
}

I want to use the variable ConnStr in the file: frmLogin.cs

frmLogin.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LVSetup.Class;

namespace LVSetup
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
        }

        private void btnEnter_Click(object sender, EventArgs e)
        {            
            string a = PublicSettings.ConnStr;
        }
    }
}

But there is no ConnStr within PublicSettings, just (Equals and ReferenceEquals)

What could be wrong here?

Upvotes: 1

Views: 13013

Answers (2)

D Stanley
D Stanley

Reputation: 152521

For a connection string, I would either use a Configuration file (app.config) or make the property a static read-only property (since there's often no reason to change a connection string at run-time):

class PublicSettings
{        
    public static string ConnStr
    {
        get
        {
            return "Connection";
        }
    }
}

Upvotes: 1

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

You need to make this field static in order to access it without creating a class instance. Or create and instance. What suites the best depends on the logic that you want to apply for this class and how it will be used later.

Instance approach

private void btnEnter_Click(object sender, EventArgs e)
{            
    var settings = new PublicSettings();
    string a = settings.ConnStr;
}

Static field approach

class PublicSettings
    {        
        private static string _ConnStr = "Connection";

        public static string ConnStr
        {
            get
            {
                return _ConnStr;
            }
            set
            {
                _ConnStr = value;
            }
        }
    }

Upvotes: 6

Related Questions