I just came across something strange, and I posted it here because although it is C# it is still part of learning ASP.NET.
Usually when you use setters and getters, you have proper methods to set and access private variables (I'm referring to C++ and JAVA mainly) but here in C# you seem to have setters and getters methods and then this strange syntax:

public class Product
{
    private string name;
    private decimal price;
    private string imageUrl;
    public string Name
    {
        get
            {
                return name;
            }
        set
            {
                name = value;
            }
    }

What on earth is that? So Name is effectively a public variable here isn't it? And how about get and set? what are they? Methods?!

Recommended Answers

All 14 Replies

Name is a property of Product. Get and set are accessors.

Say you create an object from the product class... You can set the Name value and also get its value.

 Product p = new Product();
 string n = p.Name;  // gets 
 p.Name = "Product1";  // sets

So while it seems that they act as methods because they "do" stuff, they aren't called methods.

But why not doing it the usual way via a setter/getter method? I don't get (no pun intended) that!?

Usual way? Do you mean using this shortcut method (auto-implemented properties)?

 public string Name { get; set; }

This example is the equivalent to this one...

public string Name
{
     get
     {
         return name;
     }
     set
     {
        name = value;
     }
}

Why do it the long way? Well, you may need to introduce more logic in your get/set process. The shortcut method can be used when you need the basics with no additional logic.

No, I meant the way it is done in any other OO language, with set and get methods, like this (example taken from http://www.csharp-station.com/Tutorial/CSharp/lesson10)

using System;

public class Customer
{
    private int m_id = -1;

    public int GetID()
    {
        return m_id;
    }

    public void SetID(int id)
    {
        m_id = id;
    }

    private string m_name = string.Empty;

    public string GetName()
    {
        return m_name;
    }

    public void SetName(string name)
    {
        m_name = name;
    }
}

public class CustomerManagerWithAccessorMethods
{
    public static void Main()
    {
        Customer cust = new Customer();

        cust.SetID(1);
        cust.SetName("Amelio Rosales");

        Console.WriteLine(
            "ID: {0}, Name: {1}",
            cust.GetID(),
            cust.GetName());

        Console.ReadKey();
    }
}

here we have a get method and a set method

Well.. if you dont have access to the properties via getters/setters then as described in the article, the example you provided above is an alternative.

From the article you referenced...

Traditional Encapsulation Without Properties

Languages that don't have properties will use methods (functions or procedures) for encapsulation.

But I think I can live with that. What puzzles me is the usage. Let's take another example, completely unrelated, that hopefully will help me to clarify the whole thing. Here is an application:

Product.cs:

using System;
public class Product
{
   private decimal price;
    private string imageUrl;
    private string name;

    public Product(string the_name, decimal the_price, string the_imageUrl)
    {
        name = the_name;
        price = the_price;
        imageUrl = the_imageUrl;
    }
}

Default.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    private void Page_Load(object sender, EventArgs e)
    {
        Product saleProduct = new Product("Kitchen Garbage", 49.99M, "garbage.jpg");
        //Response.Write(saleProduct.GetHtml());
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Product Test</title>
</head>
<body></body>
</html>

Pretty simple: a few private variables, when I create the new object, the constructor is called and the attributes values specified in the object creations are copied into the private variables. That's it. That's the way I'd do it.
How about this instead (Default.aspx stays the same):
Product.cs

using System;
public class Product
{
    public string Name { get; set; }
    private decimal price;    
    public decimal Price
    {
        get
        {
            return price;
        }
        set
        {
            price = value;    
        }
    }

    public string ImageUrl { get; set; }
    public Product(string the_name, decimal the_price, string the_imageUrl)
    {
        Name = the_name;
        price = the_price;
        ImageUrl = the_imageUrl;
    }
}

I saw this example somewhere in the book I'm reading. What's this nonsense?! What is the point of having public variables like Name and ImageUrl in this case if we don't have any private version of them? I mean, the point of accessors is to access private variables through public ones, but here except for price which has a private and a public version so to speak (meaning a private price that can be accessed through the public Price), Name and ImageUrl are only public...and they have their own accessor, but the accessors here are pointless, aren't they?! This example really confused me.

But I think I can live with that.

sure, in the example you provided... i dont see any problem with either approach.

What's this nonsense?! What is the point of having public variables like Name and ImageUrl in this case if we don't have any private version of them?

I've read a few intro books and you'll find slightly different approaches. Why do it one way vs another... So I'm probably not the best at this point to answer or provide you with the reasons since computer science was not my major so i dont have the theory/science portion of this field... I learned on my own so i use hte approach that best fits the problem im trying to solve. I am sure that much of my coding and style of coding may seem infintile to seasoned programers.

but lets see here..

What is the point of having public variables like Name and ImageUrl in this case if we don't have any private version of them?

You actually do have the private version... .NET is handing that private for you.

but the accessors here are pointless, aren't they

I see your point where you see that there are different ways to accomplish this, but in your last example... were are looking at object oriented programming. Your previous example without the use of properties and no get/set is really more like procedural programming...at least the way that I see it. I think you are also comparing very simple examples... in more complex programing you are going to be limited if you are just using methods/procedures.

Thanks for that, yes I supposed you're right, that's the approach the author has decided to take.

You actually do have the private version... .NET is handing that private for you.

What do you mean exactly by that? Just to clarify, I was referring to the last example where you have only one private variable, Price, the other ones, Names and ImageUrl are public. So, are you saying that Names and ImageUrl have their own private counterparts implicitly declared somewhere?

So, are you saying that Names and ImageUrl have their own private counterparts implicitly declared somewhere?

Yes, if you declare it this way... public string Name { get; set; }, .NET handles the private variable for you.

Yes, I've seen that syntax, but I had no idea that .NET handled the "private" versions behind the scene. So what does .NET exactly do, if it is not too difficult to explain/understand with the private variables?

I couldnt comments on all of the details other than this is just a shorthand/shortcut approach. I beleive you can access the private variable within the class.

this.name or just name.

OK thanks. Do you happen to know a good tutorial specifically on this as the book I have doesn't really go too much into it

I first came accross this concept while reading an asp.net c# book by Apress. I also have these bookmarks that I found that may be of help...

Accessors
Accessors

Cool, thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.