Just a short tip when using static modifier in your code. I made the image extra large this time, so you guys can see clearly. I want to make sure everyone got to know static modifiers a little better. Just remember if you create a static modifier in your code you can only access it from the class and not the instance. In the beginning I was frustrated and I wondered why I couldn't access it like from the instance or object and it was because it's weird. You can see the example below I created a static modifier and created a unit test in Visual Studio to test the property. As you can see you can only access the InstanceCount object by using the Customer class. I created 3 new customers with their first names as an example and used Customer.InstanceCount to increment by 1.
Hope you find this useful.
Static modifier-
declares a member to the class itself
Public static
int InstanceCount {get; set;}
·
Accessed using the class name
·
Not an object variable
Customer InstanceCount
+= 1;
namespace LMS.BL
{
public class Customer
{ //the static modifier belongs to the
class itself
//rather than the
instance
public static int InstanceCount { get; set; }
Lets see an Example:
[TestMethod]
public void StaticTest()
{
//Arrange
var
c1 = new Customer();
c1.FirstName = "Jan";
Customer.InstanceCount += 1;
var
c2 = new Customer();
c2.FirstName = "Bob";
Customer.InstanceCount += 1;
var
c3 = new Customer();
c3.FirstName = "Dave";
Customer.InstanceCount += 1;
//Act
//Assert
Assert.AreEqual(3, Customer.InstanceCount);
No comments:
Post a Comment