1

I am beginner in software field. And I have problem in passing Datetime to a class constructor. So there is one ASP.Net MVC 5 application and it interacts with VB.net code for backend work. (Humor me on this).

Here is what I have till now.

ViewModel:

public class Add
{
    public DateTime? dateTime { get; set; }
}

Controller:

[HttpPost]
public ActionResult AddLocationBlock(Add viewModel)
{
        if(viewModel.dateTime !=null)
        {
            ClsArgs obj1 = new ClsArgs((viewModel.dateTime);   
                                                     ^^ ERROR: matching constructor not found                                                             
        }    
        return new EmptyResult();
}

VB.net constructor definition:

 public ClsArgs(DateTime ExpirationDate);

Below solution works:

 [HttpPost]
    public ActionResult AddLocationBlock(Add viewModel)
    {
            if(viewModel.dateTime !=null)
            {
                DateTime dte = new DateTime();
                ClsArgs obj1 = new ClsArgs(dte);                                    
            }    
            return new EmptyResult();
    }
1
  • Just a note, you have this: ClsArgs((viewModel.dateTime); in your first controller block Commented May 5, 2017 at 14:30

1 Answer 1

4

You are trying to send a Nullable<DateTime> (this is what DateTime? actually means it's just a shorter version of writing it) and your constructor takes a DateTime. You have to use the Value to get the actual DateTime, after you've checked for null or HasValue otherwise you'll get an exception if it's actually null.

Change this

ClsArgs obj1 = new ClsArgs(viewModel.dateTime)

to this

ClsArgs obj1 = new ClsArgs(viewModel.dateTime.Value)
Sign up to request clarification or add additional context in comments.

5 Comments

@Unbreakable Read up on nullables. They are as robert says an object with a specific type Nullable<T>. You check whether the variable is null with help of the .HasValue property. If that returns true, then you will find the value of the object in the .Value property of the variable.
Understood, so datetime is not like a primitive datatypes. its more like a class and thus to access the value I need the instance and then the DOT operator. Thank you!
But the confusion still comes. because in the constructor I am expecting whole DateTime Object. Not a particular value out of it.
@Unbreakable, if I explained it wrong than I'm sorry, but it's exactly the opposite of what you said. DateTime behaves exactly like int, double and so on, The reason you have to use the dot operator is because you added the ?. DateTime comes from ValueType like all the structs in c#
Got it. Thank you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.