James Payne, Author at CodeGuru https://www.codeguru.com/author/jpayne/ Thu, 07 Apr 2022 16:29:39 +0000 en-US hourly 1 https://wordpress.org/?v=6.3.2 CodeGuru and VBForums Developer Forums and Community https://www.codeguru.com/news/codeguru-vbforums-forums-community/ Thu, 07 Apr 2022 16:29:39 +0000 https://www.codeguru.com/?p=19120 One of the most important ways a developer can grow and learn is by interacting with other programmers. That interaction can be as simple as a conversation or as complex as collaborating on a piece of software. Even before the pandemic and the call for social distancing, developers frequently turned to online communities to troubleshoot […]

The post CodeGuru and VBForums Developer Forums and Community appeared first on CodeGuru.

]]>
One of the most important ways a developer can grow and learn is by interacting with other programmers. That interaction can be as simple as a conversation or as complex as collaborating on a piece of software. Even before the pandemic and the call for social distancing, developers frequently turned to online communities to troubleshoot problems with code or ask for help debugging their programs and software.

Of course, most developer communities are about far more than receiving – every forum I have ever been a part of has been chock full of helpful folks who like to answer questions and pass on their programming wisdom to the younger (or less experienced) generation of coders. Teaching and helping others is another great way to learn and retain coding skills too – practice makes perfect, as they say. Plus, who doesn’t love a good coding puzzle?

Finally, developer communities are a great place to go for networking. Many a programmer has landed a job through developer forums – whether that be a long term job or just a brief freelance programming gig. And, at the end of the day, forums are not just a place to discuss all-things programming. They are a place to come and unwind, chat with online friends, and build lifelong relationships.

Developer Forums and Programmer Communities

With all of the above in mind, this week we wanted to highlight the fact that TechnologyAdvice (the people who own this – and other – websites) has several developer forums and communities in their portfolio. They cover a broad range of programming topics, including both open source and Microsoft-related.

CodeGuru Microsoft-Related Developer Forum

Software Development Forum

The first forum is CodeGuru Forums, which features 69 forum categories. While primarily focused on .NET programming topics, this community for coders also covers open source programming topics as well. The categories covered on this site include, but are not limited to, the following programming topics:

You can register for CodeGuru Forums and view a complete list of programming topics by visiting: CodeGuru Forums Registration.

VBForums Programmer Forum

Developer Forums

Despite its name, VBForums is about much more than VB.NET and Visual Basic programming. Programming languages and technologies ranging from Python to JavaScript are discussed here, alongside video gaming, and hardware-related topics. There are 60+ coding topics, including, but not not limited to:

You can register at VBForums and see a full list of coding topics by visiting: VBForums Registration.

The post CodeGuru and VBForums Developer Forums and Community appeared first on CodeGuru.

]]>
Benefits of Programming in C++ https://www.codeguru.com/cplusplus/benefits-c-plus-plus/ Fri, 04 Mar 2022 05:39:09 +0000 https://www.codeguru.com/?p=19021   C++ is one of the oldest and most widely used programming languages in the world. Part of the C-family of programming languages, it regularly places in the top five of the famed Tiobe Index, which ranks programming languages based on developer preference and usage. It is used in a wide breadth of software applications, […]

The post Benefits of Programming in C++ appeared first on CodeGuru.

]]>
 

C++ programming tutorials

C++ is one of the oldest and most widely used programming languages in the world. Part of the C-family of programming languages, it regularly places in the top five of the famed Tiobe Index, which ranks programming languages based on developer preference and usage. It is used in a wide breadth of software applications, including desktop software, graphical user interface (GUI) apps, Operating Systems, embedded systems, and video game software. In today’s programming tutorial, we will look at the advantages and benefits of developing software in C++.

What is the C++ Programming Language?

C++ is a general-purpose, statically-typed programming language with elements of object-oriented programming (OOP) and functional development. It is part of the C-family of languages, and, in fact, is an extension of C originally conceived of as C with Classes – a nod to the fact that it allows developers to use classes and objects in their code. The actual ++ portion of the name comes from C’s ++ or incremental operator, a sort of programmer joke about C++ being an incremental step-up from C. The language was created by Bjarne Stroustrup and developed by the ISO/IEC Joint Technical Committee back in 1985.

The current stable release is version C++20, which came out in December of 2020. The Preview Release – C++23 – was released in October of 2021.

In addition to objects and classes, C++ also incorporates other OOP elements, including inheritance, encapsulation, abstraction, and polymorphism. Despite this, C++ is not always considered an OOP language. It is argued that, while you can use the object-oriented aspects of C++, you do not have to. Instead, developers can take a procedural or functional programming approach to C++ software development.

Read: How to Operate on Strings in C++

What Kind of Software Can You Develop in C++?

C++ can be used to develop a wide array of software, including applications such as:

  • Video Games for consoles like PlayStation and Xbox, as well as games for PC
  • Database software
  • Operating Systems
  • Embedded systems and the Internet of Things (IoT) apps
  • Internet Browsers
  • Graphical User Interfaces and GUI-based software
  • Cloud-based software
  • Enterprise apps

Examples of software created primarily using C++ include Adobe Photoshop, MySQL database, the Mozilla Firefox Internet browser, and, perhaps not surprising, the Windows operating system.

What are the Benefits of C++

There are many reasons to use the C++ programming language to develop software and applications. Outside of its popularity and wide range of use cases. We highlight just a few of the many advantages and benefits of using C++ below.

Compatibility with the C Programming Language

Given that C++ is a derivative or extension of C and, in fact, uses practically all of the C syntax, it is no surprise that C++ is highly compatible with C. If there is a valid C application, it is compatible with C++ by its very nature.

Read: C# for Beginning Programmers

Community and Resources

As one of the oldest, most popular programming languages, C++ enjoys a vast community of developers. A large portion of that community helps add to the continued functionality of C++ by creating libraries that extend the language’s natural abilities. That same community also frequently engages in social media channels, forums, and other online (and offline) communities, helping to troubleshoot issues, provide tutorials, and document the ins and outs of the language. Because of this, it is pretty simple to find answers or solutions to problems in your code or to troubleshoot and debug your C++ applications.

Additionally, since the language is so widely used, it provides a level of job and career security, as the language will not fall off the face of the Earth in the foreseeable future, and, indeed, will continue to be supported and updated.

Platform Independent and Portability

C++ is platform-independent and portable, meaning it can run on any operating system or machine. Because of this, programs developers create in C++ will not be limited to a single OS environment or require any further coding to work on other operating systems. This increases the programmer’s audience reach and limits the amount of iterations of an application a coder will have to make.

Memory Management

With C++, developers have complete control over memory management, which, technically counts as both an advantage and a disadvantage of programming in C++. It is a bonus to developers because they have more control over memory allocation. It is a negative in that the coder must be responsible for the management of memory, instead of giving that task to a garbage collector, as other programming languages do.

Embedded Systems

As noted, C++ is a derivative of C. C, in turn, is a procedural language capable of low-level manipulation. It is similar to machine language, and because of that, C is a great option for working with embedded software and the coding of smart devices, firmware, and even compilers.

Scalability

Scalability – the ability to scale an application to serve varying degrees of users or purposes – is an important element to any modern piece of software. C++ programs are highly scalable and capable of serving small amounts of data or large amounts of information.

Read: Top IDEs and Code Editors for .NET Developers

C++ Standard Template Library (STL)

C++ has the Standard Temple Library (STL) that provides libraries – or functions – of pre-written code that developers can use to save time instead of writing common functionality in their software. These libraries make coders more efficient, type fewer lines of code, write quicker programs, and avoid errors.

Execution and Compilation Speed

C++ is a fast programming language in terms of both execution and compilation. The speed for both is much quicker than with other general-purpose development languages. Further, C++ excels at concurrency, which is important for critical mass servers, web servers, databases, and other types of servers.

C++ Hello World Example

In traditional programming tutorials, the first program a developer will learn to write in a given language is known as the “Hello, World!” application. It is a simple snippet of code that serves as a way for a coder to introduce themselves to the “world”. Think of it in the same way that most guitarists are taught to play “Smoke on the Water” by Deep Purple – it is a right of passage for programmers.

The “Hello, World!” app does not do anything spectacular – it simply prints the words “Hello, World!” to a user’s screen. Here is an example of how to write the infamous “Hello, World!” application in C++:

// C++ program that will “write “ "Hello, World!" to the user’s screen
 
// Header file for I/O functions
#include 
// The Main() function is where execution of an application starts
int main() {
    // prints Hello, World! To the user’s screen
    std::cout << "Hello, World!";
     return 0;
}

Note that the double forward slashes // are used to write comments in your code in C++. These comments are not read by the program and ignored, being only visible to developers. Comments are used to leave notes to yourself or other programmers that may be viewing your code and trying to figure out its intended use at a later date.

Read more C++ programming tutorials.

The post Benefits of Programming in C++ appeared first on CodeGuru.

]]>
.NET 6 Features – Part 2 https://www.codeguru.com/dotnet/net-6-features-part-2/ Tue, 28 Dec 2021 17:03:02 +0000 https://www.codeguru.com/?p=18829 This is the second part of our series on new features in Microsoft’s .NET 6 update. Inside, we discuss new additions to the popular programming language and platform, including how to work with file-scoped namespaces, directives and implicit global, setting application wide default fonts, and more. .NET 6 Features and Updates Before we begin, feel […]

The post .NET 6 Features – Part 2 appeared first on CodeGuru.

]]>
.Net 6 Features

This is the second part of our series on new features in Microsoft’s .NET 6 update. Inside, we discuss new additions to the popular programming language and platform, including how to work with file-scoped namespaces, directives and implicit global, setting application wide default fonts, and more.

.NET 6 Features and Updates

Before we begin, feel free to read the first part in this two-part series: .NET 6 Features and Updates.

File-scoped Namespaces in .NET

With file-scoped namespaces, we can declare the namespace for an entire file instead of nesting the remaining contents in brackets { … }. This reduces indentation tremendously.

Here is the usual syntax:

namespace MyNamespace;
class MyClass { ... } 

Here is the newer syntax in .NET 6:

namespace MyNamespace
{
    class MyClass { ... } 
}

Implicit Global Using Directives

Implicit global using directives enables us to specify using directives once and have them applied to every file that gets compiled. We can also use types defined in these namespaces without having to specify their fully qualified names.

Global using directives can be added to any source file – the best practice however is to place all of them in a single file.

Examples of the global using statement in .NET 6 follows:

global using System;
global using static System.Math;

What is interesting here is that the global modifier can be combined with the static modifier. In the above example all the methods declared in System.Math are enabled in all files in your project.

The global modifier can also be applied to a using alias directive for example:

global using Env = System.Environment;

Application-wide Default Font in .NET 6

We have all become accustomed to having Microsoft Sans Serif or Segoe UI as a default font on Windows forms. It was a bit tedious to get all the fonts and controls the same. This is simplified in .NET 6, as you can see in the following code example:

class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
        Application.SetDefaultFont(new Font(new FontFamily("Microsoft Sans Serif"), 8f));
        Application.Run(new Form1());
    }
}

Especially important to note is the fact that the Application.SetDefaultFont method should be called before the first window is created, as in the above example.

.NET 6 Target Framework Moniker

To target .NET 6 and get access to all the cross-platform APIs that .NET has to offer, make use of the net6.0 Target Framework Moniker.

For console apps, cross-platform libraries, and ASP.NET Coreapps, use the following:

net6.0

For specific operating systems, such as Windows Forms or iOS, make use of the following:

  • net6.0-android
  • net6.0-ios
  • net6.0-maccatalyst
  • net6.0-tvos
  • net6.0-windows

Notice that the above TFMs are versionless; this is because each of them is targeting the lowest supported system.

Read: Working with Files and Directories in .NET

The post .NET 6 Features – Part 2 appeared first on CodeGuru.

]]>
Tips for Writing Clean C# Code https://www.codeguru.com/csharp/tips-clean-code-c-sharp/ Fri, 08 Oct 2021 03:56:47 +0000 https://www.codeguru.com/?p=18596 Any developer can write code with enough training and practice. There are references aplenty if a programmer cannot remember how to call a function or forgets a functions parameters. Becoming a programmer is less about remembering exact syntax and more about understanding the core principles and structures of a programming language. Of course, knowing the […]

The post Tips for Writing Clean C# Code appeared first on CodeGuru.

]]>
Any developer can write code with enough training and practice. There are references aplenty if a programmer cannot remember how to call a function or forgets a functions parameters. Becoming a programmer is less about remembering exact syntax and more about understanding the core principles and structures of a programming language. Of course, knowing the syntax for the fundamentals is essential – don’t get me wrong. To become a good programmer (or a great programmer), a developer needs to take things a step further and learn how to write clean code.

What is clean code? How does a developer write clean code and avoid sloppy, “spaghetti” code? We will discuss some basic principles of writing clean, readable C# code in this programming tutorial.

Read: C# Data Types Explained

What is Clean Code?

To begin, there is no real definition of clean code; if asked, every programmer will likely have their own definition and rules. Some of those thoughts will, of course, overlap, and from that overlap, we can loosely define what clean code is.

Despite what school teachers will tell you, sometimes it is okay to assume, as we are going to do here. With that said, here it is: it is safe to assume that clean code, for most developers, means code that meets the following criteria:

  • Code is easily readable
  • Code is clearly defined and documented
  • Code is scalable per the needs of the project
  • Code is efficient and all excess code (i.e.; commented out code that will no longer be used under any circumstance) has been removed
  • Code that follows the specific best practices for that language’s best practices. In our case, that is C#.

All of that can be summarized in one simple statement: clean code is code that is easy to read, understand, maintain, and change. Period.

How to Write Clean C# Code

Here are some basic steps C# developers can take to ensure their code is clean and following best coding practices.

Use a C# Integrated Development Environment (IDE) or Code Editor

Before a developer even begins to code, they need to make sure they have an environment that will help them write the most efficient and error-free code. Whether a programmer chooses to write their applications in a code editor or integrated development environment (IDE) will depend on the developer’s personal preference or the developer tools made available to them by their development team. Whatever the case, the only way to really write clean C# code is to take advantage of a C# IDE or code editor.

The best coding environments will have features such as syntax highlighting, auto-complete, and code suggestions. All of these features help a coder better organize their code and make sure the syntax is neat and written properly. For C#, popular IDE’s and developer tools include Visual Studio, Visual Studio Code, and several of the popular Jet Brains coding tools, such as Rider.

Read: Working with Strings in C#

C# Naming Conventions for Functions, Variables, and More

Each programming language has its own set of rules for the proper naming of variables, functions, and the like. C# is no different in this respect. When naming objects in your programs, such as variables, always be certain to follow naming convention rules, such as the case objects should be named in (for example: camelCase, PascalCase, and _underscore).

In C#, naming conventions include the following:

  • Parameters: lowerCamelCase
  • Variable: lowerCamelCase
  • Class: PascalCase
  • Method Name: PascalCase
  • Method Argument: camelCase
  • Property: PascalCase
  • Public Field: UpperCamelCase
  • Private Field: _lowerCamelCase
  • Constants: PascalCase
  • Constructor Name: PascalCase
  • Namespace Name: PascalCase

Also, when naming variables and functions, be certain to name them something that makes sense and describes their intent. For instance, let’s say you want to create an int variable that will represent a date of birth – you should avoid giving it a generic name such as:

int date;

Instead, you should give it a name that you – or a future developer – can immediately recognize the intent of the variable:

int dateOfBirth;

C# Code Formatting

Every development team should have a style guide and that style guide should include how code will be formatted. In particular, you will want to decide whether your team is using spaces or tabs to indent code. There is a lot of debate in the developer community over which is, technically, better to use (meaning which is more efficient) – that is not an argument we need to have today! The point is, however, that you do need to make a decision if you want your code to be clean. Make a choice between the two options and stick with it; do not mix your spaces and tabs!

A side note: this is another reason why a code editor or C# IDE can come in handy – most will automatically handle this aspect of code formatting for you, leaving your brain to focus on other matters, such as what name your pets gave you.

Commenting C# Code

If writing clean C# code means writing code that is readable and understandable, then making sure you properly comment your code only makes sense. This should be a part of your best coding practices anyway – for your own sake if not every one else’s that will ever view or work with your applications.

Commenting, believe it or not, can be done poorly. It is not enough to just randomly slap some comments here and there in your program. Developers need to write good, quality comments just as much as they need to write clean code. For example, avoid leaving comments that are unnecessary or literally say exactly the same thing that your code does. For example, look at this line of code and its preceding comment:

class Program
{

static void Main(string[] args)
{
///  Print "My name is James Payne and I am the World's Greatest Writer!"

	Console.WriteLine("My name is James Payne and I am the World's Greatest Writer!");
}

In our above code, we created a program that prints a very true statement to the user’s screen. At a glance, any developer could tell you what that block of code does, so the comment we added offers zero value or help. In fact, all it serves to do is clutter our code by adding more distractions.

In cases where the code is self-explanatory, feel free to not leave comments. If you find yourself writing lazy comments that explain your reasoning behind writing the code in the first place – versus explaining what the code does – then consider changing the code itself. You should never have to convince anyway why you wrote code; having to do so could indicate that your code is not optimal.

Read: Commenting Best Practices for C#.

Concatenation in C#

Here is a fun C# no-no: string concatenation in loops. Avoid the use of the concatenator operator – or ‘+‘ – in loops. This can lead to some unwanted and unplanned results, leading to errors in your program or unexpected outputs. Instead of writing:

string test = "";

for (int i = 0; i < arrayOfNames.Length; ++i)
{
	test = test + arrayOfNames[i];
}

You should use the StringBuilder concatenation method instead. For example, the above code would instead read:

StringBuilder namesApp = new StringBuilder();
for (int i = 0; i < arrayOfNames.Length; ++i)
{
	namesApp.Append(arrayOfNames[i]);
}

string test = namesApp.ToString();

Pay Attention to Change Logs

As technology changes, programming languages must change as well. Indeed, programming languages, like the human languages, are ever-evolving and (mostly) improving. Because of that, a good developer will take note of their given programming languages changelogs when new version arise. One aspect of changelogs to take note of is deprecations. A deprecation in a changelog refers to a change to some element of the language whose use is now being discouraged, but not prohibited. For instance, Thread.Resume and Thread.Suspend have been deprecated in C# because they can lead to deadlocks. However, they still, technically, exist within the language and a developer could use them.

The majority of the time once something is deprecated in a version of a language, it will be slated to be removed entirely from a major update of the language later on down the line. As such, when a new developer looks at your code, they may not even recognize the deprecated part of code you input, let alone the fact that the code will cause errors once it is updated (if it does not already – that element was deprecated for a reason!).

Keep up with changelogs and be forward-thinking to keep your code clean even after you have written it.

Read: Working with Math Operators in C#

Handling Exceptions

There are some definite things to look out for when handling exceptions or when exceptions are thrown. These include the following scenarios:

  • Do not throw exceptions in a finally block, as this can mask previous exceptions in the try-catch block.
  • Do not use non-public exceptions; all exceptions should be public.
  • Avoid throwing general exceptions such as Exception or SystemException.
  • Explicitly throwing an exception can interfere with the debugging process; call throw instead.
  • Avoid throwing exceptions from the following: GetHashCode, ToString, static constructors, Object.Equals, implicit cast operators, and comparison operators (==, !=, <, <=, >, >=).

Do Not Use the goto Statement in C#

As a young developer, coding in QBasic, I learned the errors of relying on the goto statement, as it invariably led to the dreaded “infinite loop” in my programs. I was eight – I have never forgotten the lesson, all these years later.

There are some cases where a goto statement is useful and, perhaps, even recommended, but when you can, avoid its use, as it can make the program flow difficult to understand. When possible, use other control structures such as break, continue, for, or even an if.

Refactoring C# Code

Finally, clean code is code that has any extraneous code removed from it. That is why refactoring your code is one of the best ways to make sure your codebase is clean and efficient. There are plenty of C# code refactoring tools on the market, including JetBrains’ ReSharper. You can also check out our article on Code Refactoring Tips for C# for some additional ideas.

The post Tips for Writing Clean C# Code appeared first on CodeGuru.

]]>
Working with Strings in C# https://www.codeguru.com/csharp/c-sharp-strings-operators/ Sat, 28 Aug 2021 01:41:45 +0000 https://www.codeguru.com/?p=18472 Strings in C# are defined as one or more characters that are used to represent text values. Strings are made up of any letter in the alphabet, numbers, or special characters, including #@!$%& and so forth. A string can contain one character or a whole paragraph. In this C# programming tutorial we are going to […]

The post Working with Strings in C# appeared first on CodeGuru.

]]>
Strings in C# are defined as one or more characters that are used to represent text values. Strings are made up of any letter in the alphabet, numbers, or special characters, including #@!$%& and so forth. A string can contain one character or a whole paragraph. In this C# programming tutorial we are going to look at how to create strings, some common string methods, and string operators. By the end of this article, developers will have a firm understanding of how to work with strings and use them in their applications.

Before we begin, you should have an integrated development environment (IDE) or code editor that allows you to code in .Net or C# installed. Understanding the basics of C# data types is helpful as well. If you need a refresher, check out the companion article to this piece: C# Data Types. You can also brush up on C# for Beginners as well.

How Do You Create Strings in C#?

Defining C# string literals is pretty straightforward. All a developer needs to do is assign a value to the String data type, as shown in the following code:

 
using System;
 
public class StringExamples
{
            	public static void Main()
            	{
                            	string example1 = "A";
                            	string example2 = "Banana";
                            	string example3 = "This is a string as well, demonstrating using numbers 123 and symbols @#$%!";
                            	
                            	Console.WriteLine(example1);
                            	Console.WriteLine(example2);
                            	Console.WriteLine(example3);
            	}
}
 

If you run the above code, you will get the following result:

 
A
Banana
This is a string as well, demonstrating using numbers 123 and symbols @#$%!
 

The code works by creating three strings named example1, example2, and example3, respectively. We then assign a single character to example1, a word to example2, and a whole sentence that includes numbers and special characters to example3. We then use the ConsoleWriteLine() function to print out our three strings.

Console.WriteLine() is the function C# uses to print objects – which is really what a string is – to the user’s screen or console. It is one of the primary functions you will use when dealing with text values in your C# applications.

While displaying text and outputting text to the screen is a big part of working with strings, it is only one way you can use string data. In the next section we will look at some other functions you can use to manipulate text-based data and input.

Using the Escape Character in C#

There is an exception (or two) when it comes to what characters you can include in a string. Since we declare – or create – our strings by encasing them in between a set of quotation marks (” “), it makes sense that we cannot include them in a string – doing so confuses C#, as it does not know which set of quotation marks are intended to start and end the string.

There is a way to overcome this, fortunately. We can use an escape character or the backslash \ symbol prior to a double quote to ensure that C# sees it as just a regular character and not a signifier of the start or end of a string declaration.

Try out the following code to get a better understanding of how escape characters work in C#:

 
using System;
 
public class EscapeExample
{
            	public static void Main()
            	{
                            	string exampleEscape = "The man said \"Hello\".";
                            	
                            	Console.WriteLine(exampleEscape);
                            	
            	}
}
 

The output of this code is:

 
The man said "Hello".
 

If we had not used the escape character before each of our double quotes – used here to denote a quote of something someone said – our program would have ended with the following errors:

 
Compilation error (line 7, col 41): ; expected
Compilation error (line 7, col 46): ; expected
Compilation error (line 7, col 41): The name 'Hello' does not exist in the current context
Compilation error (line 7, col 46): Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
 

In addition to the \ escape character, C# offers other special characters that help to format text and strings, including:

  • \n : Newline escape to create a newline.
  • \r : Carriage return
  • \t : Tab to create a tab
  • \’ : An escape for single quote char
  • \” : An escape for double quotes in strings
  • \u: Unicode escape

Here is an example of using the backslash escape and the \t tab special character to insert tabs in a sentence:

 
using System;
 
public class EscapeExample
{
            	public static void Main()
            	{
                            	string exampleEscape = "The man said \"Hello\".";
                            	string exampleTab = "This \t is \t some \t tabs";
                            	
                            	Console.WriteLine(exampleEscape);
                            	Console.WriteLine(exampleTab);
            	}
}
 

Running this C# code in your IDE or code editor results in the following output:

 
The man said "Hello".
This  	is  	some      tabs
 

Finally, you can also escape a backslash as well – this is very useful if you need to represent filepaths, for example. To escape a backslash, you simply use another backslash in front of it. Try out the following code to see this practice in use:

 
using System;
 
public class EscapeExample
{
            	public static void Main()
            	{
 
                            	string example3 = "The file is located at: \\home\\user\\documents";
 
                            	Console.WriteLine(example3);
 
            	}
}
 

This program would result in:

The file is located at: \home\user\documents

How to use the verbatim Identifier on strings in Python

Another way to assign reserved special characters in strings is to bypass escape characters altogether, as they can become burdensome and error-prone if you have to use a lot of them. Instead, you can use the verbatim identifier – or @ symbol. Here is how the above code samples would look if we used the verbatim identifier in lieue of escape characters:

 
using System;
 
public class EscapeExample
{
            	public static void Main()
            	{
                            	string exampleEscape = @"The man said ""Hello"".";
                            	string example3 = @"The file is located at: \home\user\documents";
                            	
                            	Console.WriteLine(exampleEscape);
                            	Console.WriteLine(example3);
            	}
}
 

By adding the @ symbol before the values we are adding to our strings, we force C# to treat reserved special characters as regular characters. Note that, when we use verbatim identifiers for quoted text, we must double-up on our quotation marks surrounding the quoted text, as in the example3 string:

string exampleEscape = @"The man said ""Hello"".";

Running our previous code example would result in:

The man said "Hello".
The file is located at: \home\user\documents

The verbatim identifier can be used for much more than a replacement for escape characters. We can also use it to create multiline strings. Multiline strings are formatted strings that, when output, will be displayed on more than one line. When using verbatim identifiers to create multiline strings, you declare your string in the following manner:

using System;

namespace ExampleMultiline {

class MultiLineSample {

static void Main(string[] args) {
string multiExample = @"The man walked,
Blindly forward
Then bumped into a tree.";

Console.WriteLine(multiExample);
}
}
}

Running this in your code editor or integrated development environment would result in:

 
The man walked,
     	Blindly forward
     	Then bumped into a tree.

A final note on the verbatim identifier: it can also be used to escape certain reserved keywords, including for, if, and public. However, that topic is beyond the scope of this article. For now, just be aware that verbatim identifier serves many purposes in C#

Joining Strings and String Concatenation in C#

A common function when dealing with strings is to join one or more together. This is known as concatenation. There are several methods a developer can use to concatenate strings in C# and we will be looking at a few of them in this section.

String Concatenation Operator or + Operator

The first method involves using the C# string concatenator operator – also known as the + operator. It is a pretty simple operator to use, as exhibited in the following code that shows how to join strings in C# with the concatenator operator:

 
using System;
 
public class ConcatenationExample
{
            	public static void Main()
            	{
                                            	
                            	string firstName = "James";
                            	string lastName = "Payne";
                            	
                            	string fullName = "My name is " + firstName + " " + lastName;
                            	
                            	Console.WriteLine(fullName);
            	}
}
 

In this code, we create two separate strings: firstName and lastName. We assign each a value and then create a third string called fullName, which we assign the value of some “My name is “. We then append – or concatenate – the additional values of firstName and lastName. This make the full value of fullName equal to “My name is James Payne”. We this when we execute the last line of our code, which is a WriteLine statement whose purpose is to write the value of fullName to the screen. When you run this code in your code editor, you get the result:

My name is James Payne

C# String Interpolation

Another way to join strings in C# is to use string interpolation. This method requires a developer to place the $ symbol at the beginning of the variable assignment, as shown in the example below:

 
using System;
 
public class ConcatenationExample2
{
            	public static void Main()
            	{
                                            	
                            	string firstName = "James";
                            	string lastName = "Payne";
 
                            	string fullName = $"{firstName} {lastName} is my name.";
                            	Console.WriteLine(fullName);
                            	
            	}
}
 

Using string interpolation is the preferred method to join strings in C#. Part of this has to do with issues that can arise when you use loops and the string concatenation operator together, which can lead to some issues with looping logic.

The result of this code is that it prints the text: “James Payne is my name” to the screen.

String.Concate Method in C#

C# has a method that is specifically designed to concatenate strings – the string.concate method. It can join strings, string objects, and arrays of strings or a combination of those types, into a string. Here is how it looks in code:

using System;
 
public class ConcatenationExample3
{
            	public static void Main()
            	{
                                            	
                            	string firstName = "James";
                            	string lastName = "Payne";
            	
                            	string fullName = string.Concat(firstName, lastName);
                            	Console.WriteLine(fullName);
                            	
            	}
}

Running this code in your C# IDE will output: “JamesPayne”. Note the lack of a space between the two joined strings. You will need to account for this in your programs if you opt to use the string.Concat method.

Converting Strings to Uppercase in C#

There are times when a developer needs to convert the case of a string from uppercase to lowercase or vice versa. There are many reasons for this: for form validation, to make processing data easier, and so forth. C# has several built-in methods that can help change the case of a string. We will look at two of them in this section.

To convert an entire string to uppercase, we use the C# String.ToUpper() method. Here is some sample code showing it in action:

using System;
 
public class UpperExample
{
            	public static void Main()
            	{
                                            	
                            	string fullName = "James Payne";
                            	
                            	Console.WriteLine(fullName);
                            	string upperMyName = fullName.ToUpper();  
                            	Console.WriteLine(upperMyName);
 
            	}
}

In this example, we start by creating a variable called fullName and assign it a value. Next, we use Console.WriteLine() to write “James Payne” to the screen. We do this to show the current case of fullName, which is a mix of upper and lower. Next, we create a new variable called upperMyName and assign it the value of fullName. Before it gets assigned though, the ToUpper() method gets applied to the value of fullName, which causes the text to become capitalized. Finally, we write the value of upperMyName to the screen to show that the value has, indeed, become uppercase. The result of running this program in your IDE would be:

James Payne
JAMES PAYNE

We can also directly convert a variable to uppercase in a print statement, as in the following example:

using System;
 
public class UpperExample2
{
            	public static void Main()
            	{
                                            	
                            	string fullName = "James Payne";
                            	
                            	Console.WriteLine(fullName);
                            	Console.WriteLine(fullName.ToUpper()); 
                            	Console.WriteLine(fullName);
 
            	}
}

When we run this code, we see that the variable fullName starts out as a mix of upper and lower case text. We then use the ToUpper() function in a print statement to convert the text to all uppercase for a single instance. This means that our string is not actually changed, but, instead, a single instance of it is created. This is showcased in the next line of code, which once more prints the value of fullName, which demonstrated that the value is still a mix of upper and lowercase letters. Here is the result of running this code:

James Payne
JAMES PAYNE
James Payne

Converting Strings to Lowercase in C#

Converting strings to lowercase in C# works the same way as converting them to uppercase, except that developers must use the String.ToLower() method instead of the String.ToUpper method. Here is an example of lowercase string conversion in C#:

using System;
 
public class LowerExample
{
            	public static void Main()
            	{
                                            	
                            	string fullName = "James Payne";
                            	
                            	Console.WriteLine(fullName);
                            	string upperMyName = fullName.ToLower();  
                            	Console.WriteLine(upperMyName);
 
            	}
}

Likewise, we can also directly convert a string to lowercase by applying ToLower() to a print statement:

using System;
 
public class LowerExample2
{
            	public static void Main()
            	{
                                            	
                            	string fullName = "James Payne";
                            	
                            	Console.WriteLine(fullName);
                            	Console.WriteLine(fullName.ToLower()); 
                            	Console.WriteLine(fullName);
 
            	}
}

String Methods and Functions in C# and .Net

We have only just touched the surface when it comes to the ways we can work with strings in C# and .Net. We will continue to look at other C# string methods and functions that let developers work with text-based data and string data types in the coming weeks, so be sure to check back often for more C# programming tutorials.

Read: Working with C# Math Operators.

The post Working with Strings in C# appeared first on CodeGuru.

]]>
Working with C Sharp Math Operators https://www.codeguru.com/csharp/c-sharp-numbers-operators/ Sat, 28 Aug 2021 01:05:01 +0000 https://www.codeguru.com/?p=18470 We discussed C# data types in a previous article and today we will be following this up with a .Net tutorial that shows developers how to work with one of the data types we covered: numeric data types. Specifically, we will be learning how to use C# math operators and perform mathematical operations using C#. […]

The post Working with C Sharp Math Operators appeared first on CodeGuru.

]]>
We discussed C# data types in a previous article and today we will be following this up with a .Net tutorial that shows developers how to work with one of the data types we covered: numeric data types. Specifically, we will be learning how to use C# math operators and perform mathematical operations using C#. We will have plenty of code examples for you to practice along with, so open up your favorite integrated development environment (IDE) or code editor and let’s get started!

If you missed our previous articles in this series, we encourage you to read them. Likewise, if you need to refresh your memory, you can always revisit them by following the links below:

Math Operators in C#

Below you will find code examples showing how to work with the various math and numeric operators in C#. Some of them work in a similar manner to the mathematical operators you are used to from school and every day life. Others, while they may seem similar, work in unexpected and even surprising ways. We will begin with one of the most used operators in all of C# – the assignment operator.

Assignment Operator in C#

You have no doubt seen the assignment operator many times in your life; it is written using the equals sign or =. There are several assignment operators available in C# and the most basic is used to assign a simple value to a variable. The item to the left of the = sign is the variable name, while the value to the right of the = sign is the value that you want to assign to the variable. Here is how you use the basic assignment operator in C# code:

 
using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int age = 44;
                                            	
                            	Console.WriteLine("Age is equal to: {0}", age);
            	}
}
 

In this code, we create an integer variable named age and assign it the value 44. This is achieved in the line that says int age = 44;. Next, we use the print statement Console.WriteLine to print some text and the value of our variable to the screen. Running this code in your code editor would result in the following output:

Age is equal to 44

You can also use other variables to assign a value to a variable using the assignment operator, as shown in the following example:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int age = 44;
                            	int ageTwo = 44;
                            	int futureAge = age + ageTwo;	
                            	Console.WriteLine("Age is equal to: {0}", age);
                            	Console.WriteLine("Your age in another 44 years will be: {0}", futureAge);
            	}
}

In this example, we have created three variables. The first variable, age, represents my age. The second variable, ageTwo, represents my age when I am twice as old as I am now. Finally, we create a third variable, futureAge, which we assign the value of age + ageTwo – this shows that you can assign the value of one or more variables to another variable with the assignment operator. The result of running this code is:

Age is equal to: 44
Your age in another 44 years will be: 88

Another way to assign the value of an existing variable to a new variable would be to simply do the following:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int age = 44;
                            	int ageTwo = age;
                            	
                            	Console.WriteLine("Age is equal to: {0}", age);
                            	Console.WriteLine("ageTwo is equal to: {0}", ageTwo);
            	}
}

This results in:

Age is equal to: 44
ageTwo is equal to: 44

The Addition + Operator in C#

The addition operator – or + operator – is used in a similar fashion to its mathematical equivalent you have been using your entire life. You can use it to add two or more numbers to one another when you apply it to an integer value or a floating-point number. Note that there is a difference when you use the + operator on an int versus when you use it on a float. We will discuss that difference momentarily. First, however, check out the following example where we demonstrate how to use the C# mathematical + operator:

 
using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueOne = 12;
                            	int valueTwo = 8;
                            	
                            	Console.WriteLine("valueOne added to valueTwo is equal to: {0}", valueOne+valueTwo);
                            	
            	}
}

The result of this code, which adds the values of two integers together, is:

valueOne added to valueTwo is equal to: 20

Another way to use the + operator on an int in C# is by using it to assign a value to a variable. Check out the following code example:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueOne = 8+12;
                                                            	
                            	Console.WriteLine("The value of valueOne is equal to: {0}", valueOne);
                            	
            	}
}

Here, we create a variable named valueOne and assign is the result of the equation 8+12. The result of running this in your IDE is:

The value of valueOne is equal to: 20

Anytime that you add an integer value to another integer, the result will always be an integer value. However, if you add an integer to a floating-point number, the result is always a float. Try running the following code to see this at work:

 
using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger = 8;
                            	float f2 = 1.02f;              	
                            	Console.WriteLine("The valueInteger plus f2 equals: {0}", valueInteger + f2);
                            	
            	}
}

Running this code will create the following output:

 
The valueInteger plus f2 equals: 9.02
 

A final thing to take note of: adding two floating point numbers will, as you might imagine, always result in a float.

The subtraction – operator in C#

The subtraction operator – or – operator – in C# works much as you would expect it to. Its purpose is to perform subtraction in a mathematical equation. Again, it works the same as its math equivalent. Like the + operator, when you subtract an integer from an integer, you always return an integer value. However, subtracting an integer from a floating-point number (or vice versa), the value is always a floating-point number.

Here is how you subtract two integer values from one another with the – operator in C#:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	int valueInteger2 = 12;               	
                            	Console.WriteLine("valueInteger2 minus valueInteger1 equals: {0}", valueInteger2 - valueInteger1);
                            	
            	}
}

The output of this code is:

valueInteger2 minus valueInteger1 equals: 4

Here is some code showing what happens when you subtract an integer from a float or vice versa:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	float floatValue = 1.02f;             	
                            	Console.WriteLine("valueInteger1 minus floatValue equals: {0}", valueInteger1 - floatValue);
                            	
            	}
}

Here, the result of running this code is:

valueInteger1 minus floatValue equals: 6.98

Finally, you can also assign a value to a variable by subtracting two variables from one another and storing the result of the equation in a variable. Here is how that looks in code:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	int valueInteger2 = 12;               	
                            	int valueInteger3 = valueInteger2 - valueInteger1;
                            	Console.WriteLine("valueInteger3 is equal to: {0}", valueInteger3);
                            	
            	}
}

This code adds the result of the equation 12 – 8 – or valueInteger2 – valueInteger1 – to the variable named valueInteger3. The result of running this code in your IDE?

valueInteger3 is equal to: 4

The Mulitplication * Operator in C#

The mutiplication operator – or * operator – performs multiplication on two or more values, just as it does in mathematical equations, though you may also have used x for multiplying numbers in school, as in 4 x 2 = 8. When you multiply two integers together, your result is always an integer. However, when you multiply an integer by a floating-point number, the result is always a floating-point number. Multiplying two or more decimals, meanwhile, always results in a decimal value.

Here is an example showing how to use the multiplication * operator in C# on two integer values:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	int valueInteger2 = 12;               	
                            	
                            	Console.WriteLine("valueInteger1 times valueInteger2 is equal to: {0}", valueInteger1 * valueInteger2);
                            	
            	}
}

Here is the result of running this code:

valueInteger1 times valueInteger2 is equal to: 96

Likewise, here is some code showing what happens when you multiply an integer by a floating-point number in C#

 
using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	float valueFloat = 1.2f;               	
                            	
                            	Console.WriteLine("valueInteger1 times valueFloat is equal to: {0}", valueInteger1 * valueFloat);
                            	
            	}
}

The outcome of this code snippet is:

valueInteger1 times valueFloat is equal to: 9.6

Finally, as with the + operator and the – operator, you can of course assign a value to a variable by assigning it the result of two variables multiplied by one another. Here is a sample of that in code:

 
using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	int valueInteger2 = 4;                  	
                            	int valueInteger3 = valueInteger1 * valueInteger2;
                            	Console.WriteLine("valueInteger3 is equal to: {0}", valueInteger3);
                            	
            	}
}
 

The result of running this code would give you:

valueInteger3 is equal to: 32

The Division / Operator in C#

The division operator – or / operator – is used to divide two or more numeric values. When using the division operator, be aware that dividing an integer by an integer always results in an integer – even if there is a remainder. In the event of a remainder, C# rounds down. Consider the following code:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 7;
                            	int valueInteger2 = 4;                  	
                            	int valueInteger3 = valueInteger1 / valueInteger2;
                            	Console.WriteLine("valueInteger3 is equal to: {0}", valueInteger3);
                            	
            	}
}

Normally, if you divided 7 / 4, you would expect to get a result of 1 with a remainder of three. However, since we are dividing two integers, all that C# can return is an integer, so you get the following result instead:

valueInteger3 is equal to: 1

If you divide an integer by a floating-point number, you always receive a floating-point number:

using System;

public class Program
{
public static void Main()
{
int valueInteger1 = 7;
float valueFloat = 4.0f;

Console.WriteLine("valueInteger1 / valueFloat is equal to: {0}", valueInteger1 / valueFloat);

}
}

The result of this code is:

valueInteger1 / valueFloat is equal to: 1.75

Finally, you can assign a value to a variable by dividing two numbers and assigning their value to a variable:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 7;
                            	int valueInteger2 = 4;                  	
                            	int valueInteger3 = valueInteger1 / valueInteger2;
                            	Console.WriteLine("valueInteger3 is equal to: {0}", valueInteger3);
                            	
            	}
}

This results in the following output:

valueInteger3 is equal to: 1

The Modulo % Operator in C#

If you do want to retrieve the remainder from a division, you are in luck, because C# has a built-in math operator for just such a function: the modulo operator – or % operator. Note that using this mathematical operator only returns the remainder from the division and nothing more. Here is how you use the modulo operator in C#:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 7;
                            	int valueInteger2 = 4;                  	
                            	
                            	Console.WriteLine("The remainder of valueInteger1 / valueInteger2 is: {0}", valueInteger1 % valueInteger2);
                            	
            	}
}

Since 7 / 4 equals 1 with a remainder of 3, using the modulo will result in the output:

The remainder of valueInteger1 / valueInteger2 is: 3

Remember – only the remainder is returned when using the modulo operator.

Of course, we can use modulo to create a variable as well:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 7;
                            	int valueInteger2 = 4;                  	
                            	int valueInteger3 = valueInteger1 % valueInteger2;
                            	Console.WriteLine("The value of valueInteger3 is: {0}", valueInteger3);
                            	
            	}
}

The result of this code is:

The value of valueInteger3 is: 3

Other Assignment Operators in C#

In addition to the basic or normal assignment operator we discussed at the beginning of this tutorial, C# also offers a slew of other assignment operators. We do not have space left in this article to cover all of them, so we will have to follow up with another article to show you the rest of them. However, we can show you a few here, and give you a sneak peek of the others. Note that not all assignment operators are mathematical in nature, which is another reason we will not review them here. Some belong to Bitwise and Shift operators.

The remaining C# assignment operators include:

  • = operator A regular assignment operator.
  • += Addition assignment operator
  • -= Subtraction assignment operator
  • *= Multiplication assignment operator
  • /= Division assignment operator
  • %= Modulo assignment operator

Run the following code to see each of these C# assignment operators in action:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int additionAssignmentExample = 0;
                            	int subtractionAssignmentExample = 0;
                            	int multiplicationAssignmentExample = 1;
                            	int divisionAssignmentExample = 1;
                            	int moduloAssignmentExample = 1;
                            	
                            	Console.WriteLine(additionAssignmentExample +=5);
                            	Console.WriteLine(subtractionAssignmentExample -=5);
                            	Console.WriteLine(multiplicationAssignmentExample *=5);
                            	Console.WriteLine(divisionAssignmentExample /=5);
                            	Console.WriteLine(moduloAssignmentExample %=5);
            	}
}

The result of this code is:

5
-5
5
0
1

The += operator works by basically saying x = x +5 in this example. For instance, we started off by assigning additionAssignmentExample the value of 0. We then use the += assignment operator to add assign the value of additionAssignmentExample to itself, plus add 5 to it.

The rest of the assignment operators work in a similar fashion, only they subtract, multiply, divide, or return the modulo of the number to the right of the = sign.

The post Working with C Sharp Math Operators appeared first on CodeGuru.

]]>