Shared C# Class Code
Here's an example of a shared class in action. We're going to create a new class called SampleClass1 and define it as a public class - hence one we can access from outside SampleClass1 class code. This is a very simple class. It has two variables: an internal variable only used inside this code, testStringValue, and one which is available from outside, the public variable testString. The public variable is a property which uses get and set functions to control it's value. There aren't even any calculations here, testString is simply a string variable to hold string values.
public SampleClass1()
{
}
private string testStringValue;
public string testString
{
get
{
return testStringValue;
}
set
{
testStringValue = value;
}
}
The code behind contains the code which actually interacts with the page. It refers to tbInput which is a text box on the page and lblOutput which is a label. Only the code behind page (.aspx.cs) which is melded into the main .aspx page knows about these elements and so these lines of code must be in the code behind. Other than that, the only other line creates a SampleClass1 object called sc. It's defined in the first line of the button click event so its abilities can be tapped, in this case the testString property.
protected void btnSubmit_Click(object sender, EventArgs e)
{
SampleClass1 sc = new SampleClass1();
sc.testString = tbInput.Text;
lblOutput.Text = sc.testString;
}
Therefore, when the submit button is clicked, a SampleClass1 object, sc, is created. The testString property of sc is set to the value of tbInput's text value. (ie tbInput's text value is passed into SampleClass1's set function as the "value" and assigned to testStringValue.) When lblOutput's text value is set to sc.testString, it retrieves the value which we originally grabbed from the text box. (ie SampleClass1's get function returns the value of testStringValue and passed to lblOutput's text value.)
Now, why go to all this trouble just to create a string variable? Welcome to ASP.NET where a lot of the examples are pretty stupid. There really is no reason why you would go to all this trouble just to store a string value, however, this is a Microsoft help exercise. And a very important one given the importance of shared classes. However, it is a simple understandable demonstration to help get you started. Go ahead. Type something into the text box. When you click the submit button, the new SampleClass1 object will be created, your text stored in it (in the testString property). It will then appear in the label underneath the Submit button.
Skip to Main Points