Post: [C#] Explicit Operators
09-22-2015, 03:40 PM #1
Hash847
Purple God
(adsbygoogle = window.adsbygoogle || []).push({}); Someone suggested that I might as well make a explicit operators tutorial also.

What are Explicit Operators?
Explicit Operators are basically what allows casting. When you do
    
int ExampleInt = (int)3.14159265359; //3.14159265359 is a double but because we casted it to an int it was rounded off to 3

It goes through an explicit operation to remove the float precision.

Why would I use Explicit Operators over Implicit Operators?
To be perfectly honest, I never use Explicit Operators. I think I've used them once before. Implicit Operators are definitely the better way to go (if anyone has an actual reason why you'd want to use them let me know)

That's pretty neat.. So how do I make my own?
You can do it like so;
     
struct ForumDateTime { //just something I grabbed out of my API
string datetime;
string Date;
string Time;
int day;
int month;
int year;


public static explicit operator DateTime(ForumDateTime forumdatetime) { //changed it to explicit
return DateTime.Parse(forumdatetime.datetime); //So I felt like a bit of an idiot here since DateTime already has a parse method and works perfectly fine, but oh well.
}
public ForumDateTime(string s) {
datetime = s;
Date = s.Split(", ")[0];
Time = s.Split(", ")[1];

day = int.Parse(Date.Find("(*)-(*)-(*)")[0]); //incase you're curious what these (*)'s are they're character deliminators. anyone that matches what's to the left and right AND has the specified delimiter in the middle of it will be returned.
month = int.Parse(Date.Find("(*)-(*)-(*)")[1]);
year = int.Parse(Date.Find("(*)-(*)-(*)")[2]);
}
}


so now we can do

    
DateTime ExampleDateTime = (DateTime)new ForumDateTime("09-23-2015, 01:38 AM");


Enjoy Explicit'ness
(adsbygoogle = window.adsbygoogle || []).push({});

The following user thanked Hash847 for this useful post:

Trefad

Copyright © 2026, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo