C
C#6d ago
Faker

✅ using keyword as a directive

Hello guys, I'm a bit confused of how the using keyword is used with a namespace. Say I created a new project. At the root of that project we have a solution and inside that solution we have our project folder. Now, the namespace refers to the individual project folder we have? Consider the picture for example. The namespace is the same for every .cs file in a particular project? Why can't we do using LibraryManagement.BankAccount? What I'm trying to say is, look inside the LibraryManagementFolder and import the BankAccount class but this is incorrect to interpret it like that? Second thing, consider the following code:
C#
namespace LibraryManagement;

public class BankAccount
{
public string Number { get; }
public string Owner { get; set; }
public decimal Balance { get; }

public BankAccount(string name, decimal initialBalance)
{
Owner = name;
Balance = initialBalance;
}

public void MakeDeposit(decimal amount, DateTime date, string note)
{

}

public void MakeWithdrawal(decimal amount, DateTime date, string note)
{

}
}
C#
namespace LibraryManagement;

public class BankAccount
{
public string Number { get; }
public string Owner { get; set; }
public decimal Balance { get; }

public BankAccount(string name, decimal initialBalance)
{
Owner = name;
Balance = initialBalance;
}

public void MakeDeposit(decimal amount, DateTime date, string note)
{

}

public void MakeWithdrawal(decimal amount, DateTime date, string note)
{

}
}
When we don't use top-level statement, the namespace should explicitly been set? What the difference between a namespace and the using keyword directive here please
No description
6 Replies
Pobiega
Pobiega6d ago
BankAccount isn't a namespace, its a class. using for namespaces just "imports" that namespace so you can access it without fully qualifing ie, without using LibraryManagement you could still use BankAccount, but you'd have to write LibraryManagement.BankAccount account = new LibraryManagement.BankAccount(); etc files and directories have no direct connection to namespaces, its just convention to align them most of the time, but there are valid exceptions
Faker
FakerOP6d ago
one thing I don't understand, why even though BankAccount is in the same namespace, we need to use the line using LibraryManagement Like our IDE doesn't already know we are in the LibraryManagement project/namespace?
Pobiega
Pobiega6d ago
TLS files don't have a namespace they are namespace-less
Faker
FakerOP6d ago
ahh I thought behind the scenes we were already saying "using ...."
Pobiega
Pobiega6d ago
nope.
Faker
FakerOP6d ago
yeep I see, it's clearer now, thanks !

Did you find this page helpful?