简体   繁体   中英

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);

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM