Mihailo
Mihailo

Reputation: 65

Is this code valid? Can I have a private field in a class without public getters and setters?

This is not my code, I'm just studying how the language works, what is permitted and what isn't, so I'm learning from different examples. Is the class B correct in this instance, written this way?

using System;

namespace Testiranje
{
    class X
    {
        int x;
        public X(int i)
        {
            x = i;
        }
    }

    class B : X
    {
        int b;
    }
}

Upvotes: 0

Views: 59

Answers (2)

Fariba Mohammadpour
Fariba Mohammadpour

Reputation: 1

When you inherit a class with a constructor that has argument, you must have a constructor in derived class than call the base class constructor with it's arg. so you must write this for class B:

    public B(int a) : base(a)
    {

    }

Upvotes: 0

taiyo
taiyo

Reputation: 539

This code will give you an CS7036 compile error at class B : X. To get rid of this error, you need to provide a constructor which can call the base class constructor correctly with one argument, for example:

class B : X
{
    B():base(1) {}
    int b;
}

Nothing wrong with int b; though, there is no enforcement to add getter/setter.

Upvotes: 2

Related Questions