Skip to main content

Posts

Showing posts from 2013

C# 2.0 - Nullable Types

São 3 da manhã e não me apetece dormir. Estive a ajudar um amigo meu a trabalhar no código dele e estou apenas parcialmente cansado. Bem, porque não continuar com a série sobre a evolução do C#? Vamos a isso! Desta vez vamos falar de nullable types . Já todos utilizámos, mas no .NET 1.0 eles não existiam. Como é que representávamos um valor vazio? Uma string  pode conter null , supostamente é essa a representação do valor vazio. Como é que representamos um valor numérico vazio? Verificamos se é maior que 0? Bem, nalguns casos é exactamente isso que fazemos. Ou isso, ou criamos um valor constante que representa um "não valor". Mas para mim isto não é expressivo suficiente. Basicamente, um nullable type  é apenas um non-nullable type  envolvido na estrutura System.Nullable . Esta é uma estrutura genérica por isso faz uso dos G enerics  introduzidos no C# 2.0. A estrutura é bastante simples, contém apenas uma propriedade  HasValue  e Value . Ambas são muito explícitas e isto

C# 2.0 - Tipos Parciais

Para quem estiver interessado, encontrei uma lista muito interessante de features que foram introduzidas no C#  aqui . Esta é uma lista muito completa que contém todas as features que vou explicando uma a uma nesta série de posts. Já falámos sobre  Generics  e  Iterators . Agora vamos falar de tipos parciais . Um tipo parcial  é considerado como tal quando a sua definição está espalhada por várias partes em um ou mais ficheiros. Não tem que ser em múltiplos ficheiros, mas poderia. Este é um conceito muito simples que nos traz alguns benefícios. Vamos ver: Se um tipo for parcial, múltiplos programadores podem trabalhar em cada uma das partes. Isto permite-nos uma forma mais organizada de trabalhar, e pode acelerar a produção. Em Winforms, por exemplo, é gerada uma classe parcial  para cada Form para que o programador possa separar a lógica. Desta forma, uma parte contém informação acerca do design e a outra parte contém a lógica do  Form . A parte do design é manipulada pela fr

C# 2.0 - Iterators

Hoje vim para falar de uma das features mais úteis do C# 2.0, mesmo que muitas pessoas não saibam do que se trata. Vamos falar de iterators ! O que é um iterator? Para quem ainda não sabe o que é o padrão  iterator , podem ler a sua descrição  aqui . Um iterator  é uma classe/objecto que sabe como percorrer uma estrutura. Portanto, se tivermos uma lista de objectos, um iterator  teria o conhecimento de como percorrer essa lista e aceder cada elemento da lista. O iterator  é um design pattern  bastante conhecido e está por trás de muitas coisas fantásticas que temos hoje no .NET. (assim de repente lembro-me de LINQ ). A Microsoft definiu duas interfaces para este design pattern  chamadas IEnumerable e IEnumerator . A primeira é implementada no objecto que vamos percorrer, a segunda é no objecto que irá percorrer o primeiro. Porque é que é uma feature? Diga-se de passagem, os iterators  são um conceito bem conhecido mesmo antes do .NET existir. Sendo um design pattern  de programaç

C# 2.0 - Generics

Este é um assunto já bastante discutido pela internet fora. Todos sabemos o que são Generics , e para que são usados, certo? Não. Existe uma variedade de razões pelas quais o leitor pode não saber o que são G enerics, e algumas delas são: O leitor é novo na linguagem, O leitor não é novo na linguagem, mas nunca se deu ao trabalho de tentar aprender. Se o leitor nunca aprendeu generics, isso   não significa que nunca terá de aprender. Se reconhece este snippet, então saiba que já estamos a lidar com generics . Portanto, qual é a vantagem de utilizar generics ? Type safety Generics permite-nos apanhar erros na compilação   em vez de em  runtime,  obrigando o programador a respeitar as regras de type safety que fazem do C# uma linguagem estática. Isto leva-nos a uma produtividade acelerada porque não temos que correr o programa para saber que cometemos um erro. Por exemplo, se no snippet acima tentássemos adicionar um novo item do tipo  string, o compilador daria erro. Tip

A evolução do C# - O início

Hoje vamos falar sobre História. Não aquela História das Guerras Mundiais, mas a história da evolução do C# como uma linguagem. Tenho em mente analisar as partes principais de uma das linguagens de programação em massa mais utilizadas no mundo. A grande parte do que vou falar é fruto de muita pesquisa, em parte porque quando o C# e o .NET foram disponibilizados eu ainda não tinha escrito uma única linha de código, por isso podemos dizer que sou novato neste mundo. No entanto, estou a esforçar-me por mudar isso, e cada nova descoberta é feita com muito entusiasmo da minha parte, e eu considero-me extremamente pro-activo, o que poderá até irritar quem está à minha volta. Uma das razões pelas quais estou a escrever este post, e já agora todo este blog, é porque eu tenho gosto em aprender coisas novas e principalmente partilhá-las com outros. Chega de conversa, vamos ao que interessa! O início do .NET A plataforma .NET traz uma nova forma de programar as nossas aplicações. A Microsof

Truques com strings

Hoje, vamos falar uns truques simples com strings no C#. Eu sei que pode ser demasiado óbvio e repetido pela internet fora, mas ainda assim quero dar a minha opinão sobre o assunto. Vamos a isto! Imaginemos que temos uma List de qualquer type e vamos precisar dos seus valores separados por uma vírgula para serem enviados para uma stored procedure . O resultado desejado será, dada uma  List de {1,2,3,4}, uma string neste formato: "1,2,3,4". Como vamos resolver este problema? Já vi e fiz múltiplas soluções para o problema, por isso vamos ordenar as possíveis soluções (na minha cabeça) da mais complexa para a mais simples. Primeiro, podemos fazer isto: Vejam o quão complexo isto pode ser e o quão rapidamente se pode tornar insustentável. Quando repetido múltiplas vezes num projecto (imaginem ter isto repetido na vossa Camada de Acesso a Dados sempre que uma stored procedure  precisa deste input), isto pode tornar-se doloroso. Claro que poderiamos extrair este comportamento p

C# 2.0 - Property Acessor Accessibility

Let's talk about accessor's accessibility introduced in C# 2.0. This is a tiny little feature that can make your life easier in a number of ways. But first, let's define what i am talking about. Normally, a property is composed this way: So, from the example above, we can see that a property has a backfield (called _myProperty) and is composed by a getter and a setter . The getter is called whenever you get the value of that property. The setter is called when you set it's value. If we look carefully, we notice that the getter returns the value of the backfield, and the setter sets it's value, respectively. If we think about it, a property is nothing more than a wrapper around a private field. This way we can control all the access to that field's value. C#'s properties are nothing more than sintactic sugar for the following structure: This is an " old school property ". In languages where you don't really have the concept of prop

C# 2 - Static Members

In C# 2 there was a new addition in the functionality called static classes and members . When i say "members", i am referring to methods, properties, events and so on. I have a strong opinion about this modifier which i will share with you along the article, but let's start by looking at what "static" means. Take this code as example: Above we can see that we define two properties and one is static. In the main method we then create an instance of Person and set the normal property ( Name ). Now notice the Person.NumberOfBrains  assignment. This is the static property we created in the class. Notice that the access is made at class level , instead of instance level.  This means that there will only be one NumberOfBrains  value throughout all Person instances, but there will be a Name  value per each instance  of Person . Of course, the example is not the best, but you get the idea. Static applies when all  instances share the same value. There are some ru

C# 2.0 - Anonymous Methods

Let's get back to my series on the evolution of the C# language. Everybody is familiar with what a delegate is, right? We know that delegates are a big part of the events system in .Net. We register a method on that delegate ( called handler ) that is invoked when the delegate is invoked. In other words, a delegate simply points to a method. The advantage here is that, as the delegate wraps the method and is an object, we can simply pass it to a method as a parameter! Think about this: This is how we use a delegate in events, for instance. The class exposes the delegate and we register our method to listen it. When the delegate is called inside the class, all the registered methods will be called (because of this, we call it a Multicast Delegate ). This works well, because all you have to do is have a method with the required signature. In the example above, we needed to declare two methods just to make a Console.WriteLine. Isn't this too much? I think it's a bit to

C# 2.0 - Nullable Types

It's 3 am and i don't feel like sleeping. I've been helping a friend to work on his code and now i'm only partially tired. Well, why not continue with my series on the evolution of C#? Let's do it! So, this time i'm going to talk about nullable types . Everybody used them already, but back in .Net 1.0 they didn't exist. How did you represent a "no value present" value? Sure, string can have null, but null is different than empty, right? How do you represent an empty numeric type then? You check if it is bigger than 0? Well for some cases that's just how developers did it. Either that or create a constant value that represents a "no value". But, to me, that is not expressive enough . Basically, a nullable type is only a non-nullable type wrapped in the System.Nullable struct. This is a generic struct, so it makes use of the Generic features of C# 2.0. The struct is very simple, it contains only a HasValue and a Value proper

C# 2.0 - Partial Types

For those of you interested, i found a very interesting list of features that were introduced in C# in  here . This is a very complete list that contains all the features, and i'm explaining them one by one in this post series. We've talked about  Generics  and  Iterators . Now it's time for some partial types . A partial type  is a type which definition is spread across one or more files. It doesn't have to be in multiple separated files, but can be. This is a very simple concept that can give us many benefits, let's see: If a type is partial, multiple developers can work on every part of it. This allows a more organized way of working and can lead to production improvement.  Winforms , for example, generates a partial class for the form so that the client can separately edit other parts it. This way, a part contains information about the design and the other contains the logic of the form. In fact, this is a very spread pattern across .Net. Entity Frame

The evolution of C# - Part III - C# 2.0 - Iterators

It's been a while since i wrote the last post, but i did not forget my purpose of creating a series that shows the evolution of C#. Today i came here to talk about one of the most useful features of C#, even if you dont know you're using it. Let's talk about iterators ! What is an iterator? For those of you who didn't read about the iterator pattern somewhere in the internet or in the "Gang of Four" book, you can read a description  here . The iterator is a class/object/whatever which knows how to traverse a structure. So, if you have a list or collection of objects, an iterator would have the knowledge of how to traverse that collection and access each element that it contains. The iterator is a well known design pattern and is behind many of the wonderful that we have nowadays in .NET (Linq comes to mind). Why is it a feature? Truth be told, an iterator is a concept well known way before .NET even existed. Being an OO Design Pattern, the iterator has

The evolution of C# Part II - Generics

This is a well discussed matter throughout the internet. Everyone knows about generics, what they do and what they are used for, right? No. There is a variety of reasons why you wouldn't know about generics, and some of them are: You are new in the language You are not new in the language but never cared to learn it Simply because you never learned the basics about generics, it doesn't mean you've never used it. If you recognize this snippet, then you are already dealing with generics: So, what is the advantage of generics? Type safety Generics will allow you to catch the errors at compile time rather than runtime by enforcing the rules of type safety that make C# a statically typed language. This leads to increased productivity because you don't have to run the code to know that something is wrong. For example, if in the snippet above you tried to add a new item of type string, a compiler exception would be thrown. Typically, in C# 1.0, you would use an

The evolution of C# Part One - The beginning

Today, let's talk about some history. Not that World War history, but the history and evolution of C# as a language. I would like to analyze the principal parts in one of the mainstream languages of mass production in today's software. Beware that most of what i am about to say is the fruit of much research, in part because when C# and the .NET became available i had not written a single line of code yet, so you can say that i am a newborn in this world. I'm inclined to change that, though, but every new discovery is done with much enthusiasm on my part, and i'm very proactive, which sometimes may upset my colleagues. One of the reasons i'm writing this article - and this blog all the same - is because i love to learn new things and share it with others. Enough talk, let's get to the point! The beginning of .Net The .NET platform brings a brand new and fresh way of programming your applications. Microsoft created the term "Managed Code" to refer t

A tip on strings

Today, let's look at a simple trick with strings in C#. It may be too obvious and repeated around the internet, but nevertheless i want to give my 2 cents on the subject. So, let's start! Imagine you have a list of any type and now you will need this values separated by a comma in order to be processed in some stored procedure. The desired output for a list of  {1,2,3,4} is a string like this "1,2,3,4" . How will you solve this problem? I've seen and done multiple approaches. Let's order the possible solutions (in my mind) from the most complex to the simpler. First, we can do: Notice how complex this can be, and how fast it can become messy. When replicated across an entire project (imagine the nightmare of having this replicated in your Data Access Layer whenever a stored procedure needs this input), this can be a pain. Of course, you could extract the behavior and create an extension method for it, but as we will see, it is not necessary. Our second

Introduction

Introduction My name is Mário Constantino, i'm Portuguese and i love what i do. I work as a junior developer at a small company for 2 years-ish now. This is where i started my career, so i'm still young and have the enthusiasm that comes with the age :) Our primary area is the development of ERP software in .NET technologies interacting with SQL. This gives me a little experience, but i'm far from an expert in the area, although i'm learning a lot each day. Blogging is a new experience for me, so you'll excuse me if i make some rookie mistakes. I've been on the internet since i can remember, but only on the consumer side, never on the producer. Well, for what it's worth, now i'm going to start to produce blog posts! But first, English is not my primary language, and some typos are in order. If you catch one, please tell me in a comment. I'm Portuguese, but i thought that by making the posts in English i would get a broader audience. Also, the