1 of 43

Team 302 Software Training

C# Programming

2 of 43

Activity 0

  1. Log onto the computer
  2. Get a thumb drive
  3. In the VSCodePortable run VSCodePortable.exe
  4. Then use File -> Open Folder to open the Workspace on the thumb drive

3 of 43

C# Programming

  • Text case and Spaces
  • Blank Lines, Comments and Executable Lines
  • Variables
  • Expressions
  • Conditionals
  • Classes/Subclasses/Objects
  • Attributes/Methods
  • Calling Methods

4 of 43

Text Case and Spaces

  • Everything is case sensitive, so
    • Abc is not the same as abc or as aBC, etc.
  • Spaces also matter as abc is not the same as a bc
  • Can be between things but not within things (e.g. variable names cannot have spaces, but spaces can be after the variable name and before the next operator).

Hint: This will be one of the greatest sources of compile errors

5 of 43

Blank Lines

  • Blank Lines
    • Neither comments nor executable
    • Help make the code more readable (with a reasonable number of blank lines)

6 of 43

Comments

  • Comments
    • Used to document code; don’t document the obvious
    • What are you trying to do, Algorithm details, etc.
    • Block Comments start with /* and ends with a */ everything between is a comment
    • Line comments start with // (goes to the end of that line)
    • A line Comment that starts with another / (three slashes ///) generate documentation automatically

Hints:

  • Can be written before the code (often helps to organize thoughts)
  • Often beneficial when someone else needs to look at your code

7 of 43

Activity 1

  • Open DragonGamePad.cs
  • How many line comments are there?
  • Are any line comments on the same line as an executable lines?
  • Are there any comments that create automatic documentation?
  • How many block comments are there?
  • How many blank lines are in the file?

8 of 43

Activity 2

  • Open DragonGamePad.cs
  • How many line comments are there?101
  • Are any line comments on the same line as an executable lines?26
  • Are there any comments that create automatic documentation?51
  • How many block comments are there? 0
  • How many blank lines are in the file?24

9 of 43

Executable lines

  • Executable lines (everything else)
    • Typically end with a semicolon (;)
    • Blocks will start with a curly bracket { and end with a curly bracket }
      • Don’t have semicolons on the lines themselves
        • Executable lines inside do

Hints (common sources of compile errors):

  • Forgetting the semicolon
  • Missing the closing (ending) curly bracket }

10 of 43

Executable Lines

Executable lines can span multiple physical lines. For instance, these are the equivalent:

Abc = a + b +c;

Abc =

a +

b +

c;

11 of 43

Activity 3

  1. Open snippet.cs
  2. Inside the curly brackets DriveWithJoysticks

public override void DriveWithJoysticks()

{

⇒ Look here

}

  • Find 7 things that are wrong with the file that will make it not compile and fix them.

Hint: What are some of the common things that cause compile errors?

12 of 43

Variables

Defines a type and a name

  • Use descriptive names
    • Descriptive variable names:
      • Makes your code more understandable
      • Means you won’t need a comment to tell someone what the variable means
      • Makes it less likely that inadvertently change it
  • Can initialize where it is defined or on a separate line (but always initialize)
  • Format:

VariableType variableName = initialValue;

13 of 43

Common Variable Types

  • int - integer value (number without a decimal point)
  • float - number with a decimal point
  • double - number with a decimal point (more accuracy)
  • bool - true or false
  • enum - short for enumerated list which is a fancy integer value where the values get names.

14 of 43

enum - enumerated list

  • Default start is 0
  • Each item can have a value, but typically doesn’t
  • Useful for giving descriptive names to constant integer values
  • Example:

enum MECHANISM_TYPE

{

UNKNOWN_MECHANISM = -1,

GRABBER,

LIFT,

CLIMBER,

SIDE_HANGER,

ACTIVE_GRABBER,

MAX_MECHANISM_TYPES

};

15 of 43

Variables - Examples

int loopCount = 1;

float motorSpeed = 1.0;

bool isButtonPressed = false;

bool isGamePiecePresent = false;

float proportionalConstant;

proportionalConstant = 0.2;

16 of 43

Math Expressions

“Sequence of operators and their operands for a computation”

Assignment:

a = b;

a += b;

a -= b;

a *= b;

a /= b;

Increment / Decrement:

++a;

a++;

--a;

a--;

Arithmetic:

a = b + c;

a = b - c;

a = b * c;

a = b / c;

a = b % c;

Hints:

  • Working with integer variables may not yield desired results (it might truncate because integer math is used)
  • Before dividing you should ensure the denominator is not 0.0.

17 of 43

Activity 4

  1. Open LimitValue.cs
  2. Inside the curly brackets GetInRange

public static double GetInRange

(

double value, /// <I> - value to check

double minValue, /// <I> - minimum value for the range

double maxValue /// <I> - maximum value for the range

)

{

⇒ line goes here (after block comment)

}

  1. Define and initialize a double variable named output
  2. Based on the description what should be the initial value?

18 of 43

Variable Scope

  • Visibility within curly brackets {} (including inner or sub curly brackets, but not outer curly brackets). So, below variables defined in 1, can be used in 2 and 3, but variables declared in 3 can only be used inside 3.

{ // 1

{ // 2

{ // 3

}

}

}

  • Declaring a variable inside inner curly brackets {} creates another variable

19 of 43

Constants and Literals

Things we use (typically initial values or right hand side of assignments):

  • true / false
  • Explicit numbers (e.g. 82, 3.14159)
  • Explicit strings (e.g. “Front Left Motor”)

20 of 43

Activity 5a

public void RunMethod()

{

If ( buttonPressed )

{

double value = 1.0;

}

value = 0.5; // this value is not declared and will have a compile error

}

How can this be fixed?

21 of 43

Activity 5b

public void RunMothod()

{

double value = 0.0;

if (buttonPressed)

{

double value = 1.0; // new variable, value not reset

}

else

{

value = 0.5; // changes the value from 0.0 to 0.5

}

}

How can this be fixed?

22 of 43

Conditionals

  • Controls flow of execution based on a comparison
    • == (equals): returns true when left and right values are the same, otherwise returns false
    • != (not equals): returns true when left and right values are not the same, otherwise returns false
    • > (greater than): returns true if the left value is larger than the right value, otherwise returns false
    • < (less than): returns true if the left value is smaller than the right value, otherwise returns false
    • >= (greater than or equal to): returns true if the left value is larger than the right value or if they are equal, otherwise returns false
    • <= (less than or equal to): returns true if the left value is smaller than the right value or if they are equal, otherwise returns false

Hint: Common mistake is to use = instead of ==

23 of 43

Conditionals - if, if/else, if/else if/else

  • Evaluates the conditional executes the next block if it is true
  • else if and else blocks only get evaluated if the previous ones are false
  • Special case for booleans: conditionals don’t need an explicit conditional comparison (e.g. == true).
    • Instead if( bool ) is true or if ( !bool) is false
  • Compound conditionals
    • && is and
    • || is or
    • () can be used for groupings

Hint: Try to avoid complex compound comparisons, it is easy to make a mistake.

Careful with 2 ifs next to each other without the else both get evaluated

24 of 43

Conditionals - if

Examples:

if ( isButtonPressed )

{

}

if ( !isButtonPressed )

{

}

if (isButtonAPressed && isButtonBPressed )

{

}

25 of 43

Conditionals - if / else if / else

if ( loopCount < 5 )

{

speed = 0.5;

}

else if ( loopCount < 10 )

{

speed = 0.75;

}

else

{

speed = 0.0;

}

if ( loopCount < 5 )

{

speed = 0.5;

}

if ( loopCount < 10 )

{

speed = 0.75;

}

else

{

speed = 0.0;

}

What is the value of speed if loopCount is 3?

26 of 43

Activity 6

  • Continue modifying TeleopControl.cs
  • Find TODO: #1
  • Create conditional statements to set output if he values are larger than the 1.0 or smaller than the -1.0

27 of 43

Conditionals - switch /case

  • Compares for equal (integers or enumerated list items)
  • Starts with the switch indicating what you are going to compare
  • case for each comparison value
  • default for other cases
  • Use a break at the end of each case to avoid running into the next case.

Hint: Always have a default case.

28 of 43

Conditionals - switch / case

int abc;

int value = 0;

switch ( abc )

{

case 1:

value = 5;

break;

case 2:

value = 10;

break;

default:

value = -1;

break;

}

int abc;

int value = 0;

switch ( intValue )

{

case 1:

value = 5;

case 2:

value = 10;

break;

default:

value = -1;

break;

}

If abc is 2, the value is set to 10. If the abc is 10, the value is -1. Notice the right column case 1 is missing a break. What is value if abc is 1 for both sides? Is it the same or different?

29 of 43

Classes and Objects

  • Class == Recipe for an object
    • Subclasses are more specialized recipes that share characteristics with a (base) class. Example:
      • Vehicle is a base or parent class
      • Car and motorcycle are subclasses
  • Object == a class that has been realized, Most of the time there are multiple objects for each class

30 of 43

Classes and Objects - Example

Class: Dog

(sub)Class: GoldenRetriever

(sub)Class: Dalmatian

Objects of Class GoldenRetriever: B-Dawg, Buddha, Budderball, Mudbud, Rosebud, etc.

Objects of Class Dalmatian: Pongo, Perdita, Lucky, Patch, etc.

31 of 43

Classes and Objects - Example

Class: TalonSRX

Objects: LeftFrontDrive, LeftRearDrive, RightFrontDrive, RightRearDrive

Class: Automobile

(sub)Class: ChevyCorvette

Objects: JimsCorvette, AnnesCorvette, JaysCorvetter

32 of 43

Activity 7

Which is a class and which is an object

SuperHero

IronMan

CaptainAmerica

MarvelSuperHero

SpiderMan

WonderWoman

DCSuperHero

Batman

Gamora

Bob

Minion

Stuart

Kevin

Dave

Jerry

Mark

Phil

33 of 43

Class/Object Variables

  • Classname is the variable type
  • Initialize to null
    • Chassis drive = null;
  • Create an object using the new operator
    • Chassis drive = new Chassis();

34 of 43

Activity 8

  1. Open TeleopControl.cs
  2. Find TODO: #2
  3. Create the m_chassis object

35 of 43

Classes

  • Defined in a .cs file (file name matches the classname)
  • Using directive provides access to other namespaces
  • Define Attributes (characteristics of the objects that get created)
  • Define Methods (ways to interact with the objects that are created)
  • Attributes & Methods have visibility defined with them
    • public - everyone can see/interact
    • protected - only the class and its subclasses can see/interact
    • private - only the class can see/interact

36 of 43

Class Attributes

  • Variables that are scoped to the entire class (it can be accessed anywhere in the class).
  • Each object will have their own attributes (they are not shared). So, in the corvette example above
    • JimsCorvette may be black with a manual transmission
    • AnnesCorvette may be red with a manual transmission
    • JaysCorvette may be yellow with an automatic transmission
  • Always use private visibility
    • private double speed;
  • Should get initialized in the constructor

37 of 43

Class Methods

  • Ways to interact with the objects (functions)
  • Special Methods:
    • Accessors (get attribute values)
    • Mutators (set attribute values)
      • Generally don’t make public mutators, rather have public methods that do something that will call the appropriate mutators or set the attributes directly
    • Constructors (same name as class)
      • Gets called when an object is created using the class definition (new classname)
    • Destructor (~ plus the class name)
      • Gets called when the object gets destroyed

38 of 43

Class Layout

Provide access to other namespaces

Defines this namespace

Defines class and baseclass (:IDragonGamePad)

using Microsoft.SPOT;

using HeroDemoBots.Common.Controllers.Axis;

using HeroDemoBots.Common.Controllers.Button;

using CTRE.Phoenix;

using CTRE.Phoenix.Controller;

namespace HeroDemoBots.Common.Controllers

{

public class DragonGamePad : IDragonGamePad

{

39 of 43

Class Layout

Attributes of the class

Constructor

Method - override indicates it replaces a method in a base class

public class DragonGamePad : IDragonGamePad

{

private GameController m_gamepad;

private IButton[] m_buttonAr;

private AnalogAxis[] m_axisAr;

public DragonGamePad()

{

m_gamepad = new GameController(UsbHostDevice.GetInstance());

}

public override bool IsButtonPressed

(

BUTTON_IDENTIFIER button /// <I> - button to check

)

{

40 of 43

Reading a Method Signatures

Visibility ReturnType MethodName( ParameterType ParameterName );

  • Visibility: who can call this method (public == everyone, private only this class, protected this class and its subclasses)
  • ReturnType: what type of variable does the method call return
    • int, double, float, bool, etc.
  • ClassName: Name of the class
  • MethodName: Name of the method
  • ParameterType: type of variable being passed
    • int, double, float, bool, etc.
  • ParameterName: name of the parameter (optional). Often describes the parameter
  • Note: ParemeterType/ParameterName combination can be repeated with comma separators

ClassName objectName = new ClassName();

ParameterType ParameterName = initialValue;

ReturnType returnVariable = objectName.MethodName( ParameterName );

41 of 43

Activity 9

  • Open TeleopControl.cs
  • Find TODO: #3
  • Call the Run method on the m_chassis object
  • Open Chassis.cs
  • Find TODO: #1 and #2
  • Call the methods on m_motor described in the comments
  • Try code on test platform

42 of 43

Activity 10

  • Add documentation to:
    1. TeleopControl.cs
    2. Chassis.cs
    3. Program.cs

43 of 43

Activity 11

  • Modify TeleopControl.cs to turn the motor using a different control on the gamepad
    • Button A
    • Trigger
    • Make it switch direction based on which trigger is selected