Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi. Can someone explain me how the property .Now of DateTime has another properties in it ? For example: DateTime.Now.Year
I want to make the same thing: Accessing the property through the another one.

Thanks!

What I have tried:

Searching in Google and now asking here in CodeProject.com
Posted
Updated 29-Jun-17 23:26pm
v3

The property Now is returning the reference to an data object. That can be accessed as objects to.

You only must return an object of that type in the property getter.

Some explanation and more complex examples to getters and setters in C#.
 
Share this answer
 
It's simply because the property returns an object so you can then access the properties of the object it returns.

public class Data
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class MyClass
{
    public Data Data { get; set; }

    public MyClass()
    {
        this.Data = new Data();
    }
}


MyClass c = new MyClass();
c.Data.ID = 1;


In the above the Data property is a property of the object, if you make it static then it is a property of the type and that emulates DateTime.Now better

public class MyClass
{
    public static Data Data
    {
        get
        {
            return new Data();
        }
    }
}


MyClass.Data.ID = 1;
 
Share this answer
 
like this
public class MyDateTime {
       public static MyDateTime My_Now { get;  }
       public int My_Year { get; }
   }
int year = MyDateTime.My_Now.My_Year;

go through these links
Introduction to Object Oriented Programming Concepts in C#[^]
properties - { get; set; } - Stack Overflow[^]
Using Properties (C# Programming Guide) | Microsoft Docs[^]
static (C# Reference) | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900