Daniel Bergstrom
Daniel Bergstrom

Reputation: 55

c# how to use Property

I want to learn more about c#, and I've heard that you should use Private specifier and use get/set to make it public.

I got a small application that take textbox data and writes it to a file. And it encrypts the file.

But I can't graps the concept about getters and setters. Here is my one of my classes and Methods that writes to a file.

     class MyClass
{
     public static bool WriteToFile(string text)
    {
        string FileName = "C:\\crypt\\crypt.txt";
        try
        {
            using (System.IO.StreamWriter WriteToFile = new System.IO.StreamWriter(FileName))
            {
                WriteToFile.Write(text);
                WriteToFile.Close();
            }
            return true;
        }
        catch
        {
            return false;
        }
    }

But instead i want to use a property. How should i do it?

This is how i pass in the textbox-data from my main class.

        public void button1_Click(object sender, EventArgs e)
    {
        MyClass c = new MyClass();
        if (MyClass.WriteToFile(textBox1.Text))
            MessageBox.Show("success, managed to write to the file");
        else
            MessageBox.Show("Error, Could not write to file. Please check....");

I've looked at various tutorials such as https://channel9.msdn.com/series/C-Fundamentals-for-Absolute-Beginners/15 and tutorials, but I really stuggling.

Upvotes: 1

Views: 239

Answers (5)

nozzleman
nozzleman

Reputation: 9649

There is not much to change to your design besides one little thing. But first things first:

Could you place that code into a property? Sure. Should you? Not at all. Your method WriteToFile is actually doing sth. and thats what methods are for. Properties on the other hand are used for modifying/storing data.

Thats why property-names sound more like Names while method-names generally sound like Commands:

Example

public class Sample
{
    private string someText;

    // This Property Stores or modifies SomeText
    public string SomeText 
    {
        get { return this.someText; }        
        set { this.someText = value; }
    }

    // Method that does sth. (writes sometext to a given File)
    public void WriteSomeTextToFile(string File)
    {
         // ...
    }
}

Why properties/modifiers?

it is considered good pratice to encapsulate data within propeties like in the example above. A small improvement could be the use of an AutoProperty like so:

public string SomeText { get; set; }

which basically results in the same structure as the combination of an encapsulated field like in the first example.

Why?: because this makes it easy to switch it out or to add logic to your get/set-operations.

For example, you could add validation:

public string SomeText 
{
        // ...
        set
        { 
            if (value.Length > 100)
                throw new Exception("The given text is to long!");

            this.someText = value; 
        }        
}

SideNote: Possible improvement to your class

The only improvement I could think of is not to swallow the exception in your write method:

public void WriteToFile()
{
    using (var fileWriter= new System.IO.StreamWriter(FileName))
    {
        fileWriter.Write(_text);
        fileWriter.Close();
    }
}

This is much cleaner and you would not have to "decision" cascades handling the same issue (your try/catch and if/else) are practically doing the same.

public void button1_Click(object sender, EventArgs e)
{
    try
    {
        var c = new MyClass();
        c.WriteToFile(textBox1.Text))
        MessageBox.Show("success, managed to write to the file");
    }
    catch(Exception e)
    {
        MessageBox.Show("Error, Could not write to file. " + e.Message);
    }
}

This way, you do not only have the same behaviour, but you also have more information than just the raw fact that your operation was unsuccessful (false)

Upvotes: 1

Flavio Francisco
Flavio Francisco

Reputation: 775

Usually properties are used to keep values as attributes; characteristics; settings.

Methods and functions you would think as actions.

e.g as shown below:

public class MyClass{

/// <summary>
/// Keeps the file name
/// </summary>
public string FileName { get; set; }

/// <summary>
/// Action to write the file
/// </summary>
/// <returns>Returns true if the info. was wrote into the file.</returns>
public bool WriteToFileSucceed()
{        
    try
    {
        using (System.IO.StreamWriter WriteToFile = new System.IO.StreamWriter(FileName))
        {
            WriteToFile.Write(text);
            WriteToFile.Close();
        }
        return true;
    }
    catch
    {
        return false;
    }
}}

...

public void button1_Click(object sender, EventArgs e){

MyClass myClass = new MyClass();

myClass.FileName = @"C:\crypt\crypt.txt";

if(myClass.WriteToFileSucceed())
{
    MessageBox.Show("Success, managed to write to the file");
}
else
{   
    MessageBox.Show("Ops! Unable to write to the file.");
}}

Upvotes: 0

user5524649
user5524649

Reputation:

Without actually showing you the code I'll try and explain getters and setters so you can understand their concept.

A property looks like a method to the internal class and field to an external class.

E.g. You are able to perform logic in your property whereas when you call the property from a different class it behaves just like any other field.

GET: Used to retrieve and return a property. You are able to perform some complex logic before actually returning your property. You are able to safely expose private variables via the Get without compromising on writing.

SET: Used to set the value of a property that may be private, constant or public. You are able to have control over the setting of the variable.

Upvotes: 1

Matias Cicero
Matias Cicero

Reputation: 26281

WriteToFile is a method.

Methods are methods, and properties are properties.

Methods encapsulate behaviour, while properties encapsulate state.

WriteToFile should not be a property, because it does not encapsulate state. In fact, it attempts to write into the file system.

An example of a property would be:

public class MyClass
{
      private bool _canWrite;

      /// Checks whether the file can be written into the file system
      public bool CanWrite 
      {
          get { return _canWrite; }
      }
}

From another class, you would call it like this:

if(myClass.CanWrite)
{
     // ...
}

Notice that CanWrite does not define any behaviour, it just defines a getter for the _canWrite field, this ensures that external classes don't get to see too much about your class.

Also notice that I define a getter only, this prevents others from setting your property.

Upvotes: 2

Mō Iđɍɨɇƶ
Mō Iđɍɨɇƶ

Reputation: 331

Okay so I think for you case you don't need a property, but if we assume you wan't to create some kind of wrapper class that handles all your writing to files you could do something along the lines of

class AwesomeFileWriter
{
    private const string FileName = "C:\\crypt\\crypt.txt";
    private readonly string _text;

    public AwesomeFileWriter(string text)
    {
        _text = text;
    }

    public bool WriteToFile()
    {
        try
        {
            using (System.IO.StreamWriter WriteToFile = new System.IO.StreamWriter(FileName))
            {
                WriteToFile.Write(_text);
                WriteToFile.Close();
            }
            return true;
        }
        catch
        {
            return false;
        }
    }
}

Upvotes: 1

Related Questions