Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x

C#

92K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
2
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
2
Code Performance
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
1
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a few months or a few weeks to get market trend inform.
0
DelegatesInC#
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that understanding with Experts-Exchange users.
2
 
LVL 11

Author Comment

by:ROMA CHAUHAN
Comment Utility
Hi St. Jimbo,

Thanks for your valuable inputs.

As this is my very first article so I was not aware of all these points. I have submitted my article with the specified modifications.  Please review it again.


Thanks,
Roma
0
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
3
 
LVL 66

Expert Comment

by:Jim Horn
Comment Utility
Very well written, and I can see how this can be very useful.  Voted Yes.
0
 
LVL 111

Expert Comment

by:Ray Paseur
Comment Utility
0
Entity Framework 6
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
2
Exception Handling is in the core of any application that is able to dignify its name.
In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
2
Project templates provide the class structure and definition of service contracts, data contracts and other important features in 
Visual Studio for Windows Communication Foundation
. Using these predefined template helps you to write a service with minimal code interaction and it will lead you to build more advanced services for your projects.

There are four different types of templates present in Visual Studio. The first two are the most commonly used to build, test and deploy SOA architectural applications.
 
1. WCF Service Library:
The WCF Service Library project (C#) consists of three files; IService1.cs, Service1.cs and App.config. The WCF Service Library project (VB.Net) is consists of three files; IService1.vb, Service1.vb and App.config.

This type of project is suitable when we are focused on building the services first and deployment later.
  • IService File: This is the interface where the WCF service attributes are applied. In this file you place the definitions of data contract methods/operations.
  • Service File: This file is inherited from IService interface file and includes the implementations of defined interface's data contract methods/operations. 
  • Application Configuration File: In this file, you place the definitions of secure HTTP binding, endpoints of services and other important features.

2. WCF Service Application:
The WCF…
0
You can find plenty of algorithms on the Internet that provide the Encryption - Decryption functionality. One of them is the AES algorithm. AES stands for "Advanced Encryption Standard".

The Advanced Encryption Standard was established by US National Institute of Standards and Technology in 2001. It was based; on the work of two Belgian cryptographers, Joan Daemen and Vincent Rijmen, who submitted the proposal to NIST during the selection process.

In the AES algorithm, there is a terminology we use called 'Cipher Mode'. There are different types Cipher Modes present in the algorithm. Based on your specific needs and requirements you can select the Cipher Modes. Let's have a look at what these are and how they differentiate from other cipher modes.

1. Electronic Code Book Mode: This mode doesn't require any feedback to be applied. You pass the plain text/data using this and and get the resulted Cipher data from it directly. The main disadvantage is that this mode will return the same cipher data on passing the same type of plain text in loop; if you pass 'Hello, World!' three times in this mode then it will return same cipher data in each iteration. That is why this mode is considered as 'Vulnerable' and not recommended for use.

2. Cipher Block Chaining Mode: This mode is required to add the feeback to modify the pre-encrypted data; with the feedback it will make each cipher data…
1
New feature and membership benefit!
LVL 10
New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Mulithreading is a wonderful concept but it is one of the most complex way to achieve a task. Microsoft had provided probably the most efficient way to handle this problem by using async calls and thread pool. This provides an easy way to handle more than one task in an efficient way. But the biggest problem is thread creation and disposal of thread in this programming scenario. A common problem we are facing with UI programming is we are executing a task which takes a long time.

And if we are trying to do the same in Main Thread of application it freezes the UI until the completion of job. For example in the given program we are trying to run infinite loop and trying the display the count on textbox

 
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private TextBox textBox1;
        private Button btnStart;
    
        public Form1()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.btnStart = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // btnStart
            // 
            this.btnStart.Location = new System.Drawing.Point(134, 27);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(75, 23);
            this.btnStart.TabIndex = 0;
       

Open in new window

0
Hi,

There are a lot of written methos of getting the difference between two dates, but I couldn't find the one I needed. I need to have a real difference like 3.75 months between the two dates.

Not every month has the same amount of days and the February is also an issue here. So I made myself a method doing this:

/// <summary>
/// Get months difference between two dates
/// </summary>
/// <param name="from">from date</param>
/// <param name="to">to date</param>
/// <returns>months (double) between </returns>
internal static double GetMonths(DateTime from, DateTime to)
{
	/// |-------X----|---------------|---------------|--X-----------|
	///         ^                                       ^
	///       from                                     to

	//change the dates if to is before from
	if (to.Ticks < from.Ticks)
	{
		DateTime temp = from;
		from = to;
		to = temp;
	}

	/// Gets the day percentage of the months = 0...1
	///
	/// 0            1                               0              1
	/// |-------X----|---------------|---------------|--X-----------|
	/// ^^^^^^^^^                                    ^^^^
	/// percFrom                                    percTo
	double percFrom = (double)from.Day / DateTime.DaysInMonth(from.Year, from.Month);
	double percTo = (double)to.Day / DateTime.DaysInMonth(to.Year, to.Month);

	/// get the amount of months between the two dates based on day one
	/// 
	/// |-------X----|---------------|---------------|--X-----------|
	

Open in new window

3
 
LVL 3

Author Comment

by:TGB01
Comment Utility
Hi mahmuod,

I know, but using this you get the real difference between two dates, like the days between the two dates (Double). In the TimeSpan, there is no Month property.

And in my case, the method is using one month as 100%, so every month can have different amount of days. So the same amount of days between two dates can have multiple results depending on the choosen dates.
0
 
LVL 1

Expert Comment

by:SimonPrice3376
Comment Utility
because of the complexity of the question, have you mapped out the sum on paper?  

if you can get the sum right using proper math, you should then be able to recreate the sum in a method \ function and return the value accordingly.
0
Sometimes when developing windows forms application, it becomes an important part of application design to persist the state of windows form after it is closed.

One such example that comes to my mind is an application called “Sticky Notes”.

Here the user is expected to open a notepad which she can re-size as and when required, can write few notes on it and then close this form. The notes are to be saved in a persistent storage like Database or XML.

Next time when the user opens that sticky note, it should open in the same size and display the notes that were written by the user last time.

As far as persistence of the notes to Database and/or XML file is concerned, I know there are many ways to do it. This article however deals with the second part of the problem, i.e. persistence of the form state in the application.

Some people might argue that if we can save note’s data in DB/XML we can also save form’s State. But, i personally feel that since form’s state is the data related to user interface, so it should be persisted somewhere in the application.

So let’s begin this tutorial by understanding the problem statement first:-

The Problem Statement

During the flow of an application, a windows form is opened. The User the re-sizes the form, make some other activity with the form and closes the form. Next time when the user opens this same form again, the size of the form should be same as when the form was closed.

Solution

Looking at …
4
 
LVL 8

Expert Comment

by:TheMozz
Comment Utility
Great article! I especially appreciate the comment about separating the application data from the UI specific data. It is easy to forget the difference when working on an app that has to be done "Right Now" (not that things are ever done that way..).
0
 
LVL 16

Expert Comment

by:Easwaran Paramasivam
Comment Utility
Excellent Article!!
0
This article is for Object-Oriented Programming (OOP) beginners.

An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Interface member. In C# multiple inheritance is achieved with the help of Interfaces.

Therefore, if the Development Team is large or 3rd-party vendors are involved, then it may possible that two team members may end up creating two different Interfaces with the same method name. Consequently, as a developer you may have to implement both these Interfaces in one Class.

Scenario: So let’s assume that –

You have two different Interfaces let’s say ICustomer and IVendor. Both the Interfaces have a method with same name let's say GetData().

GetData() from ICustomer would return the list of customer names while GetData() from IVendor would return the list of vendor names. In the data access layer, a single class CompanyDAL implements both these Interfaces.

See attached Code Snippet for Interface definitions –
using System.Collections.Generic;

namespace ExplicitInterfacesSite
{
    // Simple interface for Vendor class
    public interface IVendor
    {
        // Return the list of vendor names
        List<string> GetData();
    }

    // Simple interface for customer class
    public interface ICustomer
    {
        // Return the list of  customer names.
        // This function name is conflicting with 

Open in new window

3
Introduction
Hi all and welcome to my first article on Experts Exchange.
A while ago, someone asked me if i could do some tutorials on object oriented programming.

I decided to do them on C#. Now you may ask me, why's that?
Well, one of the reasons was that i have more C# than C/C++ knowledge.
Another one is that C# is becoming more and more a very important language, and forces you to think object oriented, wich is a style of programming were lots of people who are used to traditional techniques have trouble understanding with.
And last but not least, when you combine C# with the powerfull Microsoft XNA Framework it becomes fairly easy to create games that work on both PC and Xbox and even on Windows Phone 7.

Also, i decided to write them, instead of making video's.
Video's are handy, but not that functional when it comes to programming (imo). When you want to explore something in between, you have to pause them, remember where you were, you need audio so not development in the middle of the night with your wife sleeping next to you and lots of other downsides.
Also my English pronouncing is far from perfect.
Maybe i will make a video sometime when i really want to show something special, but changes are low.

I'm not a fulltime software developer as i'm also responsible for a part of the network management in the company where i work, but i'll try to do my best to make things as clear as possible for you all.
If someone finds an error in my ways of …
1
 

Expert Comment

by:krg2
Comment Utility
Excellent work, Japy!

I truly appreciate your tutorial, it is very helpful and provides a good reference
0
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can be easily solved by simply using a graphics creation tool such as Paint, Gimp, or Adobe Photoshop and the Transparency key tool found within the C# program.

To ensure you have the correct amount of space for all form objects needed and even room for adding features down the road, design of your new program becomes the key to a successful build. In keeping with that tradition of design we will need to first layout how we would like our form to look at the end of our project.

For this example we will be creating a mock MP3 Player. I have decided to make the form appear in the shape of a banner with the display information and buttons in the center. Here is how I would like my form to look when it is complete:

 image001.jpg

As you can tell I am not an artist but for the purpose of this article let’s pretend it is the greatest design ever. You can do this step with nothing but a scratch piece of paper and pen just so you have a visual goal to work towards. Next we want to conceptualize a layout on the form to see if it meets your needs.

image002.jpg

Once again, despite the artistry it appears to be in line with my concept.

The next step is where we turn idea into reality. From here going forward…
3
This article introduced a TextBox that supports transparent background.

 TCTextBox demo

Introduction


TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the urge for it. TextBox is among one of them, but unfortunately, once in a while people want it to be transparent (such as this typical question in EE: Transparent TextBox in C#).

If you search on the internet for a solution, you will come across advices like subclassing TextBox and add the support to transparent background color, or, drawing your own background in the OnPaint event. It is rational theoretically but unfeasible practically, as revealed in the following analysis.

(For those who like fast food, you can skip the literature sections and jump to the “Using the Code” section to grab and eat. Actually I also get my hands wet immediately after a short hunting with no luck. After a couple of days working, when I decide to present this home-made component to public, I have to head back to the anatomization part to make the article complete. It costs me much more time than doing the simply coding stuff along.)

The traditional TextBox just refused to be tweaked


To verify the above common suggestions, I build a phantom class TestTextBox derived from TextBox. Again, test cases are flagged in the source code for users who like to practise by themselves.

Set background color as Color.transparent (Test Case 1)
1
 
LVL 8

Author Comment

by:trestan
Comment Utility
systan, would you mind post the link where you see the same TXTextBox? Did you compare the source code bwtween the two?

It's also normal that not only one person think about the needs and create something similar:)
0
 
LVL 8

Expert Comment

by:mac-will
Comment Utility
You aren't Disposing your 'SolidBrush' object.

You should wrap the new solidbrush in a using.
0

Summary:

Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to-use code snippet using BinaryFormatter with simple encryption is provided.


Introduction:

I was amazed the first time I read the dotnet documentation about serialization. Prior to the dotnet era, it was a big headache to deal with configuration data. You would have to write large code pieces to stream the data out to a file and then parse the long strings again to find out the proper data to read back. When playing with serialization, I was hoping to create a complete cache of the application and restore it just like nowadays Windows system “Hibernation” feature. Although the reality is always far from the imagination, dotnet serialization is still very useful in caching “part” of an application – the data objects.

Dotnet framework provides two types of serialization: shallow serialization, and deep serialization, represented by
   XmlSerializer in System.Xml.Serialization namespace and
   BinaryFormatter in System.Runtime.Serialization.Formatters.Binary namespace,
respectively. The differences between the two types are obvious: the former is designed to save and load objects in human-readable XML format, and the latter provides compact binary encoding either for…
4
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods.
Demo
Introduction

In one of my applications I needed a control that could be resizable at run time. Just like the canvas in MSPaint, you can resize it inside the host window. After a quick search on the internet I noticed that most solutions treating this simple issue as a beast.  An example of a "complex implementation" is in the EE Solution, here.

Using SendMessage is an intuitive temptation.  We could try the technique I descried in my previous article on how to drag a form -- wehe we simply flood mouse movement to the caption of the host form.  However, the parameters for resizing message scattered to eight directions and you'd have to calculate the delta in each direction to make it work.  That’s why the code tends to become so bulky.


Using PictureBox as decoration

When a control is runtime resizable, you'll certainly want to provide some visual indication to users. You can manually draw an “edge” on the control using graphic functions, and manually change the cursor type when the …
0
 

Expert Comment

by:Asus314
Comment Utility
can you please share source code of your soft TcPaint ?
Thank you
0
Concerto's Cloud Advisory Services
LVL 4
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Introduction

Although it is an old technology, serial ports are still being used by many hardware manufacturers.

If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to work on many clinical instruments as a job requirement to parse, extract patient test results and send them to a database backend for reporting. This means there are many serial ports attached to the computer.  I developed different C# applications for each instrument. However, whenever I needed to make any changes, I had to open source code of the application, compile and deploy over and over again. It was very time consuming and a headache.

This is why I developed a serial port programming language:  To reduce development time.  I have made the tool available as project on SourceForge.  In this article, I'll discuss some of its features and give you an idea of how to use it.


Application Features

It is a handy, simple application specially designed to simplify the development of RS232 based applications. It makes it easy not only to communicate with the serial port but also data parsing and extraction.

It requires .NET Framework 3.5 or above and supports all major Windows platforms including Windows XP, Windows Vista and Windows 7.

Key Features

Able to log multiple serial ports at the same time. The data logger has the capability to log multiple ports simultaneously so that
3
 
LVL 49

Expert Comment

by:DanRollins
Comment Utility
This looks like an excellent tool.  You got my YES vote, above!

One of the very first projects I worked on (back in about 1980), was an interpretive language for use in controlling a modem during the log-in process when connecting to remote host systems (such as CompuServe).  It is VERY useful to be able to just tweak a script and retry -- much better than re-coding!
0
 
LVL 4

Author Comment

by:albay
Comment Utility
I got the first YES vote from you. That is great.

Yes, I hate re-compile big projects over and over again.That is why I developed this application.
by the way I will appreciate, if you can change the link.

Thank you again.
0
Introduction

This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would get that off the bat and you are one of them you should understand by the end of the Part 1.  Part 2 will deal with creating objects and inheriting from IDisposable.

With wonderful things like disposable objects and garbage collection I feel most of our developer colleagues have forgotten about memory management and memory leaks. If you are one of those people who would say: “There is so much memory available these days we don’t need to worry about memory”, then you fall into 1 of 2 categories.

You have not developed anything more complex than a “hello world” app
You are a VB developer
Either way you don’t need to continue reading. (This article is meant for developers) ?

Before getting into the article consider the following priorities when developing:
Code must execute as fast as possible (yes I mean shaving off 1/(1 000 000) of a millisecond)
The application must be as small as possible (no useless processor executions)

How to use an object of type IDisposable

Let’s assume that you want to open a connection to Sql Server. There are 2 ways to do this with executing the .Dispose() method. By the way – you have to …
2
 
LVL 75

Expert Comment

by:käµfm³d 👽
Comment Utility
You are a VB developer
Not sure why VB developers are being singled out here. IDisposable is a .NET concept, not a C# or VB concept. It exists in both languages (even C++.NET and F# have it), and its intent is the same. Speaking of which...

...you have to call .Dispose() on a disposable object to free it from memory.
The intent of Dispose is not to release the object being disposed from memory. Its intent is for the programmer to trigger the object to release any unmanaged resources that the object may be holding on to. IDisposable has no bearing over when the object itself will be purged from memory by the GC. The GC itself has no knowledge of unmanaged resources, which is why Dispose exists. Dispose is for the programmer to explicitly trigger the release of unmanaged resources; Finalize (what you referred to as a "destructor") is an implicit trigger of the same.

With regard to using statements, there are actually times when a using is counter-productive--though, most times it is advisable to use a using.
0
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any questions.

WCF can not be directly called by VB6; we need to create a .NET bridge for it.  Below is how to create that bridge.

Create a .NET Class Library project

1. What all functionality are intended to be used in COM, create an interface for it.  The interface should be public and with the [ComVisible(true)] attribute.  If WCF is to be called, then this interface will be same as the contract interface in WCF (except attributes OperationContract and ServiceContract will not be added in .NETBridge interface.)
2. Create .NET class implementing this interface. (Here write all functionality i.e. logic, call service, hit db …)
3. Class should be public and should have following attributes
   a. [ClassInterface(ClassInterfaceType.None)]
   b. [Guid("<A GUID>")]
   c. [ComVisible(true)]
4. In Visual Studio, right click the project node in Solution Explorer.  Go to Properties -> Signing
5. Check Sign the assembly. Create a new key (using the dropdown control).
6. Build your application.
7. Open Visual Studio command prompt.
8. Use regasm /tlb:<urDesiredTLB>.tlb  <urDLL>.dll   i.e.
      regasm /tlb: wcfCaller.tlb wcfCaller.dll
1
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions.
Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column.

First solution, the easy way
The first solution is to make the column slim enough, so that the record selectors are not drawn: the are on the left side of the column. Set the property RowHeaderWidth to a value less than 20, but this value depends on the style you used...

Second solution, the long way
OK, you can always redraw your items completely, by doing the work "by hand"...
This is what I found by Googling; it is in C# language, but I think it's easy to understand.

 void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs  e)

        {

            if (e.ColumnIndex == -1 && e.RowIndex > -1)

            {

                e.PaintBackground(e.CellBounds,true);

                using (SolidBrush br = new SolidBrush(Color.Black))

                {

                    StringFormat sf = new StringFormat();

                    sf.Alignment = StringAlignment.Center;

                    sf.LineAlignment = StringAlignment.Center;

                    e.Graphics.DrawString(e.RowIndex.ToString(),

                        e.CellStyle.Font, br, e.CellBounds, sf);

                }

                e.Handled = true;

            }

        }

Open in new window


Third solution, the smart way

I prefer this solution. I don't know if anyone (and it is probable) have already posted something similar, in this case I apologize :-)
This solution is the middle-way of the others. It is simplier and doesn't need to draw anything: just ask the datagridview to do the job for you.


Open in new window

0
C# And Nullable Types

Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a database column for instance) and assigning a value will change the result.
Nullable type is applicable to primitive (known as value) types where data is stored in the stack and .NET Framework implicitly initializes them to their default values, even though the developer did not do that. Applying Nullable type to primitive types helps going round discomfort of looking for equivalent decisions like creating:

A boxed value type. This is not strongly-typed at compile-time, and involves doing a heap allocation for every type.
A class wrapper for the value type. This is strongly-typed, but still involves a heap allocation, and the you have to write the wrapper.
A struct wrapper that supports the concept of nullability. This is a good solution, but you have to write it yourself.

Nullable types can be declared in two ways:
System.Nullable<T> variable
T? variable

Open in new window

T is the underlying type of the variable. It can be a struct but cannot be reference type.

Any value type may be used as the basis for a nullable type. For example:

int? i = 10;
double? d1 = 3.14;
bool? flag = null;
char? letter = 'a';
int?[] arr = new int?[10];

Open in new window

Each instance of the above inherits two public read-only properties from Nullable type:
HasValue – bool type stating that variable contains a value
Value
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
Comment Utility
You might want to make a note about what "boxing" is. I have a feeling that people who do not know about Nullable may also not know what the concept of "boxing" is  :)
0
 
LVL 22

Author Comment

by:Ivo Stoykov
Comment Utility
In brief:
(un)boxing = conversion.
value -> reference type = boxing (wraps value in a Object)
reference -> value type = unboxing (extracts value from a Object)

Here's what Microsoft says about boxing 8-)
0
Introduction
                                               
Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.
 
Also called: Implicitly typed local variables
 
The var keyword – in VB
 
I have heard many an argument about this new addition to the C# language. One of the main debates being: It’s so VB like, It reminds me of Dim.  So this is all I am going to say about its use in VB (and only because I think if VB programmers use it may make their code just a little better).
 
Its use in VB is slightly different to that in C#.  This is because VB has always had an unknown type keyword (dim), so you have to explicitly “turn on” the functionality by using the “Option Infer On” at the top of your module.  So to finish off for VB: To use this functionality turn it on and the declare your Variable like so:
 
   Dim MyStringVariable = "hello world"
 
When hovering the mouse over MyStringVariable you will notice the tooltip text says Dim MyStringVariable As String.  So you will not be able to do your usual VB thing and change its type later on to an int!
 
The var keyword
 
First of all to ease all your minds the var keyword is not evil VB code creeping into your C# IDE!  It is strongly typed (which means that you cannot put a string into it and then later on change its type to an int).
 
It must not be …
7
 
LVL 34

Expert Comment

by:it_saige
Comment Utility
Agreed on all points.

But in reality, do you have to *know* what the result of using default on a type is?  Can you just not check for type to default(type) equality [or inequality] by using:
SomeType == default(SomeType)

Open in new window

As you have attested, the list is not exhaustive and, for the most part, is intuitive.

Can I blame my last example on poor coffee intake?  ;)

-saige-
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
Comment Utility
Contrived example, but:

int x = 10;
int y = default(int);

double z = x / y;

Open in new window


I agree, it's mostly intuitive:  number types are all zero, and reference types are null.
0

C#

92K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).