user3197410
user3197410

Reputation: 133

How come "var" works without specifying the namespace?

I have the following code:

 var dataExistsResult = await _service.CheckifExists(RequestDto);
 if (dataExistsResult != null && dataExistsResult.CountProperties() > 0)
    //do something

But if i specify "var" PropertiesWithData dataExistsResult = await _service.CheckifExists(RequestDto); it doesn't work since the namespace is not included in the file:

namespace Core.Common
{
    public class PropertiesWithData
    { 

I need to set using Core.Common; for that to work. How come "var" is working when running the program? And how come it possible to access properties of "var" if it knows the type but using Core.Common; is not in the file? eg: dataExistsResult.CountProperties() Is Core.Common.PropertiesWithData added at runtime? eg Core.Common.PropertiesWithData dataExistsResult = await _service.CheckifExists(RequestDto);

Upvotes: 1

Views: 123

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456437

Namespaces are part of the type name. So when your code refers to a type (by name), it must specify the namespace one way or another.

When using var, the type is not referred to by name, so no namespace is necessary. The compiler knows what type it is because the method declaration includes the type name (including namespace).

Upvotes: 3

Related Questions