Teehee...

In-line Conditionals

Code:
if (a)
   Console.Write("Hai");
else
   Console.Write("Bai");


is equal to:


Code:
Console.Write(a ? "Hai" : "Bai");


The syntax for in-line conditionals is:
condition ? evaluates if true : evaluates if false

Now that you know this, never use it Wink
It's a very bad practice that can lead to unreadable code. It's not fun for other members of your team, so avoid doing it unless you really have to.[/b]
Not to bust your bubble or anything, but the ternary operator exists in pretty much every major programming language.
My bubble is still intact Razz I was directing this at n00bs
SirCmpwn wrote:
Teehee...

In-line Conditionals

Code:
if (a)
   Console.Write("Hai");
else
   Console.Write("Bai");


is equal to:


Code:
Console.Write(a ? "Hai" : "Bai");


The syntax for in-line conditionals is:
condition ? evaluates if true : evaluates if false

Now that you know this, never use it Wink
It's a very bad practice that can lead to unreadable code. It's not fun for other members of your team, so avoid doing it unless you really have to.[/b]


I certainly wouldn't say to 'never' use it. I use it all the time in ADTs. I'd much rather have a 1 line function than a 4 liner for things like setter and getter methods. I hate returning in a conditional, so I def prefer a ternary operator for those.
SirCmpwn wrote:
Now that you know this, never use it Wink
It's a very bad practice that can lead to unreadable code. It's not fun for other members of your team, so avoid doing it unless you really have to.[/b]


What? No. If someone on your team doesn't know or like ternary operators, they don't belong on the team. Razz The only thing to avoid is stacking four or more ternaries (three or more if you're a stickler), and to instead use a switch/case. This is ok:

Code:
message = ((errno == -1)?"General Error":((errno == -42)?"Meaning of Life Error":((errno == -1337)?"Elite Error":"Unknown/Other Error)));

This is not ok:

Code:
square = n==1?1:(n==2?4:(n==3?9:(n==4?16:(n==5?25:....)))))
KermMartian wrote:
What? No. If someone on your team doesn't know or like ternary operators, they don't belong on the team. Razz The only thing to avoid is stacking four or more ternaries (three or more if you're a stickler), and to instead use a switch/case. This is ok:

Code:
message = ((errno == -1)?"General Error":((errno == -42)?"Meaning of Life Error":((errno == -1337)?"Elite Error":"Unknown/Other Error)));

This is not ok:

Code:
square = n==1?1:(n==2?4:(n==3?9:(n==4?16:(n==5?25:....)))))


Kerm, neither of those are OK. Stacking ternaries == trip to hell.

Also, this thread totally sucks, so I'm going to make it worthwhile. If you've ever used Python, you're probably familiar with slices (and why they are awesome). Here are slices for C#:


Code:
    public static class SliceExtension
    {
        public static T[] Slice<T>(this T[] self, int start)
        {
            return self.Slice(start, self.Length);
        }

        public static T[] Slice<T>(this T[] self, int start, int end)
        {
            if (start < 0)
                start = start + self.Length;
            if (end < 0)
                end = end + self.Length;
            if (start >= end)
                return new T[0];

            int len = end - start;
            T[] buf = new T[len];
            Array.Copy(self, start, buf, 0, len);

            return buf;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var t = "12345";
            Console.WriteLine(t.ToCharArray().Slice(0, 1));
            Console.WriteLine(t.ToCharArray().Slice(-2, -1));
            Console.WriteLine(t.ToCharArray().Slice(-1));
            Console.WriteLine(t.ToCharArray().Slice(-2));
            Console.WriteLine(t.ToCharArray().Slice(2));
            Console.WriteLine(t.ToCharArray().Slice(2, -2));
        }
    }
Kllrnohj wrote:
KermMartian wrote:
What? No. If someone on your team doesn't know or like ternary operators, they don't belong on the team. Razz The only thing to avoid is stacking four or more ternaries (three or more if you're a stickler), and to instead use a switch/case. This is ok:

Code:
message = ((errno == -1)?"General Error":((errno == -42)?"Meaning of Life Error":((errno == -1337)?"Elite Error":"Unknown/Other Error)));

This is not ok:

Code:
square = n==1?1:(n==2?4:(n==3?9:(n==4?16:(n==5?25:....)))))


Kerm, neither of those are OK. Stacking ternaries == trip to hell.


I agree completely. I don't even stack 2 in my code. You should only really use a ternary operator when it's an obvious place to. You're not being clever when you stack them; you're just destroying your readability.
Anyway...
Day 2

Pointers
You probably know about pointers in every other language except C#, and wonder, "what the heck?" Well, C# has them. If you are on a calculator forum, you probably know z80 so I won't bother explaining them, but I will tell you the syntax:

Code:
int* Variable;

This initializes Variable as a pointer to an integer, rather than an integer.

For more information, go to this site: http://msdn.microsoft.com/en-us/library/y31yhkeb%28VS.80%29.aspx
Yes, you can use pointers, but why should you need to? Just pass by reference. The only time I figure it might be useful to use raw pointers rather than checked references would be if you're doing interop with unmanaged code, in which case something like the IntPtr struct is probably more useful.

Additional note, you can only use pointers in an unsafe context:

Code:
//Compiler error
int* foo;

//OK
public unsafe void foobar()
{
    int* bar;
}

//Compiles, but probably some sort of access violation at runtime
unsafe
{
    int* baz = (int*)(new Random.Next());
    Console.Write(*baz);
}


Someone put it out of its misery please...
Quote:

You probably know about pointers in every other language except C#, and wonder, "what the heck?"


No, you don't. Anyone who wanted to use them and has before in another language would have googled it.

Quote:
Well, C# has them.


No shit.

Quote:
If you are on a calculator forum, you probably know z80


I wouldn't be surprised if >50% don't. This forum rarely discusses calculator programming anymore, and even when it did, it was predominantly TI-BASIC.

Quote:
so I won't bother explaining them,


Really? But it takes sooo long to google for it. I was planning on microwaving popcorn in that minute. I'm going to starve now!

Quote:
but I will tell you the syntax:


That's good. I may still have time to toast a pop-tart now.
Quote:

Code:
int* Variable;


Wow, it's just like every other language! How useful to know!

Quote:

This initializes Variable as a pointer to an integer, rather than an integer.


Wow! I was expecting it to point to the hot babe on my desktop. Good to know!


Now, if you had mentioned unsafe blocks, the one interesting thing about C# pointers, this post wouldn't have been a COMPLETE waste of time. Sadly, however, you failed.
Thank you for going through my post and pointing out everything I did wrong! I really appriciate it.
One operator that I've known a few seasoned C# programmers to miss is the null-coalescing operator ??.

Code:
a ?? b

is equivalent to

Code:
a != null ? a : b
benryves wrote:
One operator that I've known a few seasoned C# programmers to miss is the null-coalescing operator ??.

Code:
a ?? b

is equivalent to

Code:
a != null ? a : b


Oh cool! I didn't know that one, and I have been working with C# for 5 years now.
SirCmpwn wrote:
I have been working with C# for 5 years now.


Ultimate Dev'r wrote:
SirCmpwn wrote:
I have been working with C# for 5 years now.


http://i402.photobucket.com/albums/pp110/bdubs2594/1255311593141.png


I lol'd.

Seriously though, SirCmpwn, either start posting *advanced* tricks (like LINQ and extension methods - which I already demonstrated) or ask for other people to post tricks, because this thread is like an idiots guide to an idiots guide to C#.

Note to Kerm: I think the 0x5 thing has played itself out...
SirCmpwn wrote:
Thank you for going through my post and pointing out everything I did wrong! I really appriciate it.
Haha, don't mind foamy3's bluntness, he makes a good point, but I'm glad you're understanding more programming languages more widely.

BenRyves: Nice.
LINQ
By request, I am discussing LINQ today. LINQ stands for Language-INtegrated Query, and is great for dealing with web responses, xml, or any other ordered data. This is a big topic, I'll discuss it over several days. Today, we will start with LINQ queries. A LINQ query is an instruction in your code that executes like a for loop, and extracts bits of data. There are five keywords we are interested in here:

Code:
Where
Select
SelectMany
OrderBy
GroupBy

Notice that I said "keywords." Not commands. LINQ was built into .NET 3.5 as well as C# 3.0. If we have some XML, this is how we can extract what we need from it:

Code:
// Initialize an XDocument
new XElement("contacts",
   from c in contacts.Elements("contact")
   select new XElement("contact",
      c.Element("name"),
      new XElement("phoneNumbers", c.Elements("phone"))
   )
);

This will initialize a new XElement using the XDocument c. Let's break it down.

Code:
new XElement("contacts",

This is pretty self explanitory, it instantiates the XElement we will store the data in.

Code:
from c in contacts.Elements("contact")

This says we are going to look through "contacts.Elements("contact")" and store it temporarily to c.

Code:
select new XElement("contact", c.Element("Name"), new XElement("phoneNumbers", c.Elements("phone"))

This determines how the data is going to be eventually stored into the new XElement from the beginning.

For more information, go to: http://msdn.microsoft.com/en-us/library/bb308960.aspx#xlinqoverview_topic2[/b]
Serialization
Serialization, while not unique to C#, is one of the easiest ways of storing data between sessions. It can take any object, any class, anything in your application and save it. It will also load any object from a file, and instantiate a class from the file. This basically means that to save files, you can simply add a class, use it in your code, and when you want to save it, serialize it. There are several classes you can use for serialization. The first of these is the BinaryFormatter. This class serializes and deserializes objects into a simple, binary format that has a small file size. Here is the usage:

Code:
using System.Runtime.Serialization.Formatters.Binary; // Phew!
//...
BinaryFormater Formatter = new BinaryFormatter();
Formatter.Serialize(ObjectToSerialize, StreamToSaveTo);
TypeToSerialize ObjectToSerialize = (TypeToSerilize)Formatter.Deserialize(StreamToReadFrom);

That's all you have to do! I personally think that serialization is under rated, it's really an amazing and easy way to save files and the like from your application.
SirCmpwn wrote:
This class serializes and deserializes objects into a simple, binary format that has a small file size.
Simple, yes, as it's just a complete dump of the object from memory, warts and all. This does however mean that the file is comparatively large and may break between versions of an application. Consider using the XmlSerializer instead (which only serialises public properties by default), or write your own as is appropriate for the job in hand.
Quote:
I personally think that serialization is under rated, it's really an amazing and easy way to save files and the like from your application.
How is something that is very widely used "underrated"?
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 2
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement