newDotNetGuy
newDotNetGuy

Reputation: 21

class can i use the properties of the name space from base class

Have a simple question, well looks to be simple but i have been searching for the reason could not get it back.

  1. If i have imported a namespace in base class can i use the properties of the name space ( classes, objects, method etc.) in all the derived class?

for example

using System.Collections.Generic;
public class MyBase
{
     public string GetName()
        {
            List<string> ss = new List<string>();
            return ss.ToString();
        }
}

Can i use the List property in all child classed from my base with out having the namespaces? like

public class myChild : MyBase
    {
        public string GetName()
        {
            List<string> ss = new List<string>();
            return ss.ToString();
        }
    }

If not Why? Also the same behavior i have noticed in partial classes .. can some one explain the reason behind this?

Upvotes: 2

Views: 129

Answers (2)

phoog
phoog

Reputation: 43056

using statements are not executable code, and they do not apply to classes or members of classes. Rather, they give the compiler information about how to resolve type names. A using statement is only in scope in the file in which contains it; furthermore, if it is inside a namespace declaration, it's only in force within that namespace declaration.

Note that it's possible to have more than one namespace declaration in a file, so:

namespace N
{
    using System.IO;
    partial class C
    {
        public FileInfo SomeFileInfo { get; set; }
    }
}

namespace N
{
    partial class C
    {
        public DirectoryInfo SomeDirectoryInfo { get; set; }
    }
}

The reference to DirectoryInfo can't be resolved, because using System.IO; is not in scope at that point.

Upvotes: 2

JaredPar
JaredPar

Reputation: 755141

It sounds like you're asking the following

If a Parent type is defined in a file that imports a namespace, do I have to reimport that namespace if I derive from Parent?

If so the answer is yes. A child type doesn't inherit the namespaces which are imported in the file in which the parent type is defined (partially because with partial types a type can be defined in multiple files with conflicting namespaces). Every file is compiled based on it's own set of imports.

Upvotes: 3

Related Questions