0

So I'm trying some C#. I want a class that takes strings as constructor arguments when an object is created. Then the strings are to be stored within the class. Something like this:

public class DVD
{
    public string sTitle, sName, sType;
    public int iLength=0;

    DVD(string title, string name, string type, int length)
    {

        sTitle = title;
        sName = name;
        sType = type; 

    }
}; 

As of what I've understood, the strings are just references. That's probably the reason why I get the error messages:

Warning 2   Field 'DVDsorter.DVD.sName' is never assigned to, and will always have its default       value null 

I tried to do things like

sTitle = new String(title); 

and

sTitle = new String;
sTitle = title; 

with no success.

Some useful background information could be that I'm about to read information about DVD's line by line from a textfile, and then save each DVD as objects from the DVD class above. This means that I want to deepcopy the information.

How do I best solve this probably very simple task?

5
  • 3
    You almost never need to explicitly copy strings like this. And if this is your real code, you shouldn't be seeing this error. If this is your real code, try cleaning your solution Commented Sep 12, 2014 at 3:14
  • 3
    I just compiled your code and there are no errors or warnings. What is the problem? Commented Sep 12, 2014 at 3:16
  • By the way if you instance any object, you have to use initializers(constructors) which are () and {}. I am talking about 'new String' statement. Commented Sep 12, 2014 at 3:20
  • Oo, cleaning did the trick. Never expected that error actually, thought I had misunderstood some C# concept. Thanks guys. p.s.w.g: Is this a bad solution, other ideas? Commented Sep 12, 2014 at 3:26
  • Add public identifier with your constructor. Commented Sep 12, 2014 at 4:44

2 Answers 2

1

Strings are reference types but they are immutable. So, if you say:

string s1 = "some string";
string s2 = s1;

s1 = "that was easy";

Console.WriteLine(s1);
Console.WriteLine(s2);

You will see they are difference.

I wrote this just as an explanation. I don't see the problem with your code. Maybe you have updated it since you tried to compile it?

I recommend this approach, though:

public class DVD
{
    public string Title{ get; set;}
    public string Name { get; set; }
    public string Type { get; set; }
    public int Length { get; set; }

    public DVD(string title, string name, string type, int length)
    {

        Title = title;
        Name = name;
        Type = type; 
        Length = length;

    }
}

It is just a little cleaner. I did not compile it to ensure no typos.

Sign up to request clarification or add additional context in comments.

2 Comments

Yep cleaning the compilation did the trick. What does the set; get lines do? Is called something in particular? I haven't seen it in C++, I suppose it's something specific to C#?
Yes, they are automatic properties. In C# there is this notion of properties. You can make the "get;" have special code in the body, in C# 3.5, this shortcut was added so that you could have properties with the option of adding code later, without needing to change the "interface."
1

First, a couple of tips. You should avoid public fields like the plague. If you need to expose a field, either use an automatic property:

public string Title { get; set; }

...or a property with a private backing field if you want to implement some validation (basic example here):

private string _title;
public string Title
{
    get { return _title; }
    set
    {
        if (!String.IsNullOrWhiteSpace(value) && _title != value)
        {
            _title = value;
        }
    }
}

Furthermore, I prefer to initialize properties with initial values and this can be done either through the backing field or through constructor (depending on your taste and which above choice you go with):

private string _title = ""; // or String.Empty;
public string Title
{
    // same code as above
}

// or...

public DVD()
{
    Title = "";  // or String.Empty;
}

I would much rather deal with an empty string than a null value and worrying if I implemented is a null check somewhere down the line. This is just a tip, so take it with a grain of salt. There are people on both sides of this one. You can also assign it a generic string such as "None" or something along those lines, so that would indicate that no value was assigned.

As far as your problem with the value not being assigned to the fields through the constructor... I think it's because you have a private constructor. You need to specify the public access modifier for your constructor:

public DVD(string title, string name, string type, int length) { ... }

...instead of your current:

DVD(string title, string name, string type, int length) { ... }

*Note the public access modifier in the first one.

Easy way to demonstrate this is to run this line of code:

var dvd = new DVD("Some Title", "Some Name", "Some Type", 1);

You'll get a compile-time error:

`YourApplicationName.DVD' does not contain a constructor that takes 4 arguments

2 Comments

Great! So the automatic properties is just a way of not having to create the get, set methods each time I suppose? Don't really get what's the benefit though. Those properties could have been there all the time, and then be overriden whenever necessary? I found their official example: msdn.microsoft.com/en-us/library/bb384054.aspx But they don't even use the get, set methods in the example. Is this a bad example, or does the automatic properties just enable something that isn't obvious? Because writing to the public variables could be done anyway.
@user3050215 Correct. Automatic properties cover the getter, setter and backing field (if you don't want extra validation on the backing field). The MSDN example you found shows perfectly fine how they're used. You don't use .Get() or .Set()... instead, you simply assign to them like any field/member. The benefits of the automatic properties are that you may validate what goes in or out through the getter and setter and also restrict which action you want to allow. For example, you can make it public for reading, but private for setting: public string Title { get; private set; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.