Hello i am doing a school assignment. Everything in my program works fine but the teacher wants me to add a parameter of type DateTime in one of my constructors. I am a bit confused since i think that i already have a parameter of this type:
using System;
using System.Windows.Forms;
namespace Assignment4
{
class Task
{
private string time = string.Empty;
private string date = string.Empty;
private DateTime dateTime = new DateTime();
private string description = string.Empty;
private object priorityType;
private string priority;
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public DateTime DateTime
{
set
{
dateTime = value;
time = dateTime.TimeOfDay.ToString();
date = dateTime.Date.ToString("d");
}
}
public string Time
{
get
{
return time;
}
}
public string Date
{
get
{
return date;
}
}
public object PriorityType
{
set
{
priorityType = value;
priority = priorityType.ToString();
}
}
public string Priority
{
get
{
return priority;
}
}
}
}
Is dateTime = value not a parameter of type DateTime?
The constructor of a C# class is a method without a return type and with the same name of the class. The constructor is called everytime you create an instance of the class (new YourClass).
You can have many constructors with different kind of parameters passed to these methods, even one without parameters (it is the default constructor).
The correct constructor is identified by the parameters that you pass when you create the class....
public class Person
{
private string _name;
private DateTime _dob;
public Person(string name, DateTime dateOfBirth)
{
_name = name;
_dob = dateOfBirth;
}
}
..... somewhere in your code .....
Person myself = new Person("Steve", new DateTime(1970,1,1));
Since DateTime is an immutable struct, you can only set its values from the constructor. That means you need to do something like this:
dateTime = new DateTime(2016, 05, 03);
In your case, you can just use this, since you set it somewhere else:
private DateTime dateTime;
(Also, your property needs a get too, you just have a set now)
Related
I'm studying object oriented programming. I have a class Dob, it reads the date of birth from main. If the date of birth from main was from 10 years ago until now, it says "error", else "verify".
Here is my class
public DateTime _Dob;
private DateTime dob {
get {
return _Dob;
}
set {
_Dob = value;
}
}
public Student(DateTime dob_) {
_Dob = dob;
}
public void checkdob(DateTime dob) {
DateTime local = DateTime.Now;
if (dob.Year >= local.Year - 10)) {
Console.WriteLine("error");
} else {
Console.WriteLine("verify");
}
Now I want to pass the birth date from main but I don't know how to do that. Here is what I have in main (It has errors and I don't know how to solve it):
Student dob = new Student(new DateTime(23/02/2010));
dob.checkdob( 02/12/2010);
Console.ReadLine();
First and foremost, you have the property just the wrong way around. The idea is that you expose the value of a private field through a public property, not the other way around:
private DateTime _dob;
public DateTime Dob
{
get { return _dob; }
set { _dob = value; }
}
But if you do not use the public property anyway, don't expose it.
Now, it seems strange to pass the date to the constructor of your class, and then pass it again when you want to check it. Use the value you already have.
public void CheckDdob()
{
if (_dob.Year >= DateTime.Now.Year -10))
{
Console.WriteLine("error");
}
else
{
Console.WriteLine("verify");
}
}
Then, to create a new DateTime for your constructor, just use the following:
Student dob = new Student(new DateTime(2010, 02, 23));
And finally, you may want to review your logic, because you do not actually check correctly if a date is more than 10 years ago. Then again, what you have may fit your requirements.
You will need to use a proper constructor parameter for DateTime. There are plenty of them listed here.
You can start with using this one,
new DateTime(2010,02,23)
Just an example on how to solve this:
using System;
public class Student
{
public Student(string name, DateTime dateOfBirth)
{
Name = name;
DateOfBirth = dateOfBirth;
}
public string Name { get; private set; }
public DateTime DateOfBirth { get; private set; }
}
public static class Helpers
{
public static bool IsOlderThen(this DateTime date, TimeSpan age)
{
var now = DateTime.UtcNow;
return now - date > age;
}
}
public class Program
{
public static void Main()
{
var adult = TimeSpan.FromDays(365 * 18);
var studentOld = new Student("Alice", DateTime.Parse("1998/04/17"));
var studentYoung = new Student("Bob", DateTime.Parse("2015/04/17"));
Console.WriteLine("isAdult: " + studentOld.DateOfBirth.IsOlderThen(adult));
Console.WriteLine("isAdult: " + studentYoung.DateOfBirth.IsOlderThen(adult));
}
}
I'm trying to use a nested class to get two classes to pass into a single argument so I can send it to a backgroundworker. Thus far, I've managed to pass single arguments into a backgroundworker but I'm yet to do it with a nested class where I end up passing both or my desired classes into the same argument. So far here is some of the code I'm using:
This is the Nested Class I'm attempting to use:
public class MyBackGroundWorkerObject
{
public class TimeZone
{
public string Zone;
public int difference;
public override string ToString()
{
return Zone;
}
}
public class AccountName
{
public string AccountSid;
public string AuthToken;
public string Name;
public override string ToString()
{
return Name;
}
}
}
Here's an example of one of the classes in action:
MyBackGroundWorkerObject.AccountName acct = new MyBackGroundWorkerObject.AccountName();
//AccountName acct = new AccountName();
acct.AccountSid = "abcd";
acct.AuthToken = "xyz";
acct.Name = "Potato";
ddlAccounts.Items.Add(acct);
MyBackGroundWorkerObject.TimeZone region = new MyBackGroundWorkerObject.TimeZone();
//TimeZone region = new TimeZone();
region.Zone = "UTC";
region.difference = 0;
comboBox1.Items.Add(region);
And here's the part where I'm utterly confused, I'd like to be able to use both of these when calling from the Window's Form from where it's retrieving some of the entered data. I'm not sure on how to get both of these classes to work in conjuction where I can send them both at the same time to the backgroundworker:
MyBackGroundWorkerObject myBackGroundWorker1 = new MyBackGroundWorkerObject();
object obj = ddlAccounts.SelectedItem;
MyBackGroundWorkerObject.AccountName acct = obj as MyBackGroundWorkerObject.AccountName;
backgroundWorker1.RunWorkerAsync(acct);
You defined the nested classes inside MyBackGroundWorkerObject but there is no variable of type TimeZone nor of type AccountName declared inside the MyBackGroundWorkerObject class.
public class MyBackGroundWorkerObject
{
public class TimeZone
{
public string Zone;
public int difference;
public override string ToString()
{
return Zone;
}
}
public class AccountName
{
public string AccountSid;
public string AuthToken;
public string Name;
public override string ToString()
{
return Name;
}
}
public TimeZone TheTimeZone {get; set;}
public AccountName TheAccountName {get; set;}
}
Now you can set your instances via the TheTimeZone and the TheAccountName members respectively and access them when you pass the MyBackGroundWorkerObject.
MyBackGroundWorkerObject myBackGroundWorker1 = new MyBackGroundWorkerObject();
MyBackGroundWorkerObject.AccountName acct = new MyBackGroundWorkerObject.AccountName();
//AccountName acct = new AccountName();
acct.AccountSid = "abcd";
acct.AuthToken = "xyz";
acct.Name = "Potato";
ddlAccounts.Items.Add(acct);
MyBackGroundWorkerObject.TimeZone region = new MyBackGroundWorkerObject.TimeZone();
//TimeZone region = new TimeZone();
region.Zone = "UTC";
region.difference = 0;
comboBox1.Items.Add(region);
myBackGroundWorker1.TheTimeZone = region;
myBackGroundWorker1.TheAccountName = acct;
backgroundWorker1.RunWorkerAsync(myBackGroundWorker1);
Inside the background worker doWork cast it to MyBackGroundWorkerObject and access it via .TheTimeZone and .TheAccountName again
So, I have this code
Process[] processesManager = Process.GetProcesses();
List<ProcessInfo> temporaryProcessesList = new List<ProcessInfo>();
for (int i = 0; i < processesManager.Length; ++i)
{
temporaryProcessesList.Add(new ProcessInfo(processesManager[i].ProcessName, processesManager[i].Id, TimeSpan.Zero, "Group"));
}
processesList = temporaryProcessesList.GroupBy(d => new {d.Name}).Select(d => d.First()).ToList();
This code is used for getting current processes. Then I'm adding those procesess to temporaryProcessesList. And instead of simple string "Group" I want to set the property depending of the name of process. For example if process has name leagueoflegends.exe then I would like to set the group to "Games", if its devenv.exe I would like to set the group to "Software development".
And my question is, how to do it the simplest/best way? I was thinking about using Dictionary with string and enum. And comparing the ProcessName with string. But maybe there is better way to do it.
ProcessInfo is simple class with 4 properties and constructor.
public class ProcessInfo
{
private string Name { get; set; }
private int Id { get; set; }
private TimeSpan Time { get; set; }
private string Group { get; set; }
public ProcessInfo(string name, int id, TimeSpan time, string group)
{
Name = name;
Id = id;
Time = time;
Group = group;
}
}
Using dictionary is the best way to accomplish this:
var dictionary = new Dictionary<string, string>();
dictionary.Add("a.exe", "aGroup");
dictionary.Add("b.exe", "bGroup");
string val;
if (dictionary.TryGetValue(processName, out val))
processInfo.Group = val;
else
processInfo.Group = "Undefined Group";
Maybe this is what you are looking for:
public class ProcessInfo
{
private string _name;
private string Name
{
get { return _name; }
set
{
_name = value;
UpdateGroupName();
}
}
private int Id { get; set; }
private TimeSpan Time { get; set; }
private string Group { get; set; }
private void UpdateGroupName()
{
Group = ProcessNames::GetGroupFromProcessName(Name);
}
public ProcessInfo(string name, int id, TimeSpan time)
{
Name = name;
Id = id;
Time = time;
}
}
internal static class ProcessNames
{
private static Dictionary<string, string> _names;
public static string GetGroupNameFromProcessName(string name)
{
// Make sure to add locking if there is a possibility of using
// this from multiple threads.
if(_names == null)
{
// Load dictionary from JSON file
}
// Return the value from the Dictionary here, if it exists.
}
}
This design isn't perfect, but hopefully you see the idea. You could also move the update of the Group name to the constructor, but then it would not change the Group name if you set the property after construction.
Also, you could clean the interface up by using INotifyPropertyChanged and/or dependency injection. https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx
In my silverLight project I have a class on web side with few DateTime fields. I want to write Partial class for the class on client side which will return string instead of DateTime. How to write it?
This is what I tried. I added new string variable in Partial class which will get date field's and return string.
here is code:
public partial class abcd
{
DateTime date1;
public DateTime Date1
{
get { return date1; }
set { date1 = value; }
}
DateTime date2;
public DateTime Date2
{
get { return date2; }
set { date2 = value; }
}
}
public partial class abcd
{
string date1Str;
public string Date1Str
{
get { return Date1Str; }
set { date2 = Date1.ToString(MM/dd/yyyy); }
}
}
I guess Date1Str should be readonly and just look like this:
public string Date1Str
{
get { return date1.ToString("MM/dd/yyyy"); }
}
I have a class, with a public property "appController", as follows:
public class FAST
{
#region Props
public AppController.AppControllerClass appController = new AppController.AppControllerClass();
#endregion
#region Contructors
public FAST(AppController.AppControllerClass appcontroller)
{
this.appController = appcontroller;
}
#endregion
}
I have another few class, in which I would like to use the appController of FAST, the above class.They look like:
public class Forecast
{
#region Properties
private int _forecastnumber;
public int ForecastNumber
{
get { return _forecastnumber; }
set { _forecastnumber = value; }
}
private DateTime _startdate;
public DateTime StartDate
{
get { return _startdate; }
set { _startdate = value; }
}
private DateTime _enddate;
public DateTime EndDate
{
get { return _enddate; }
set { _enddate = value; }
}
private DateTime _deadline;
public DateTime Deadline
{
get { return _deadline; }
set { _deadline = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _type;
public string Type
{
get { return _type; }
set { _type = value; }
}
private string _description;
public string Description
{
get { return _description; }
set { _description = value; }
}
private string _status;
public string Status
{
get { return _status; }
set { _status = value; }
}
#endregion
#region Constructors
public Forecast()
{
}
#endregion
#region Methods
public static void InsertForecast(Forecast forecast)
{
try
{
this.appController.Execute(appController.nDC.FASTData.InsertForecast(forecast.StartDate, forecast.EndDate, forecast.Deadline, forecast.Type, forecast.Name, forecast.Description, forecast.Status));
}
catch (Exception ex)
{
this.appController.LogError(ex);
}
}
#endregion
}
I want to be able to declare the FAST class once, passing in the AppController, then use my other classes freely, and they will use the appcontroller of the FAST class.
Can this be done at all? (inheritance?)
Thanks for any help.
It sounds like you simply want a static class for your FAST class. If you define the AppController variable as static, it will be accessible from anywhere.
I would say no to inheritance. Inheritance suggests an "is" relationship, e.g. "Forecast is a specialized version of the app controller." Aggregation, a specialized form of object composition, suggests a "has" relationship, e.g. "Forecast has an app controller."
http://en.wikipedia.org/wiki/Object_composition#Aggregation
You could add a setter method to set your FAST object as a property of Forecast:
public FAST appController { get; set; }
And then
var f = new FAST(new AppController.AppControllerClass());
var forecast = new Forecast();
var forecast2 = new Forecast();
forecast.appController = f;
forecast2.appController = f;