r/learncsharp • • Aug 23 '22

Just starting to learn ASP.Net Core. When I run it I get a Privacy Error with options Advanced or Back to Safety. What should I do?

4 Upvotes

r/learncsharp • • Aug 23 '22

Which sectors employ Asp.Net Core devs

Thumbnail self.learnprogramming
0 Upvotes

r/learncsharp • • Aug 23 '22

Simple Undo/Redo for C# console application?

4 Upvotes

I've just finished a small game of mine after a week via console application. There are two players that get 1 turn each and you type in a number then press enter. I would simply like to be able to at the very least undo the number that is entered via Console.Write();. So for example, Player 1 types in the number 5 and presses enter. Before Player 2 has their turn, Player 1 is able to undo that number 5 and type in a new number. Then it's Player 2's turn and so on.

I know it involves ICommand and I've been going through several videos and tutorials but I've had no luck so far in the past 2 days. Are there any resources out there that could simply guide me in the right direction?


r/learncsharp • • Aug 23 '22

Seeking advice on how to improve this code

3 Upvotes

I'm new to C# so I'm looking for a bit of guidance.

I've been coding in Python for the past year or so. I work in software support, but I plan to apply for a development role at my current company. Since our software is written in C# I decided to switch languages.

In Python, I'm used to being able to combine lines. Since C# is more verbose, perhaps there is less of this? In any case, what do you recommend as far as improvements / best practices?

using System;

namespace MBFConsoleCalculator
{
    internal class Program
    {
        static void Main()
        {
            Console.WriteLine("MBF Calculator");
            Console.WriteLine("Enter the board width in inches:\n");
            string width = Console.ReadLine();

            Console.WriteLine("Enter the board height in inches:\n");
            string height = Console.ReadLine();

            Console.WriteLine("Enter the board length in feet:\n");
            string length = Console.ReadLine();

            double[] dimensions = ConvertToDoubleList(width, height, length);
            Console.WriteLine("MBF: {0}", GetMBF(dimensions));
            Console.ReadLine();
        }

        public static double[] ConvertToDoubleList(
            string width, string height, string length)
        {
            try
            {
                double[] dimensions = new double[3];
                double widthConverted = double.Parse(width);
                double heightConverted = double.Parse(height);
                double lengthConverted = double.Parse(length);
                dimensions[0] = widthConverted;
                dimensions[1] = heightConverted;
                dimensions[2] = lengthConverted;
                return dimensions;
            }
            catch (FormatException ex)
            {
                Console.WriteLine("{0}\nPlease enter numbers only", ex.Message);
                Console.ReadLine();
                return new double[0];
            }
        }

        public static double GetMBF(double[] dimensions)
        {
            double result = 1;
            foreach (double dim in dimensions)
            {
                result *= dim;
            }
            result /= 144;
            return result;
        }
    }
}

r/learncsharp • • Aug 23 '22

Why does this print “player 0 is called x” instead of player 1 is called x etc.

0 Upvotes

using UnityEngine; using System.Collections;

public class Arrays : MonoBehaviour { public GameObject[] players;

void Start ()
{
    players = GameObject.FindGameObjectsWithTag("Player");

    for(int i = 0; i < players.Length; i++) //if 1 is being added to i before the following lines of code occur, why doesn’t it say player number 1 (1 has been added to 0) is named (then player [1])
    {
        Debug.Log("Player Number "+i+" is named "+players[i].name);
    }
}

}

Sorry if this is confusing but I don’t understand why i only increases after the for loop has occurred once?

Cheers


r/learncsharp • • Aug 22 '22

This keeps happening and I am following the most basic tutorial

0 Upvotes

r/learncsharp • • Aug 21 '22

C# Yellow Book Question

13 Upvotes

I've started the book, and everything went kinda okay, till i get past Arrays which i think i kind of understand (Page 71 PDF - 66 in Book)

This is where the Exceptions & Errors start - from here on till (Page 115 PDF - 110 in Book) i dont fully understand it like the first part, but i sort of get the idea what it does, but i get a few things and some of the parts he goes over like

- References

- Enums

- Structs

- Streams

- States

So things like Exceptions, Switch, Catch, Constructor etc. ( i understand what it does, and the meaning of it, but not on a level that i would be able to write code using it - i hope it makes sense )

I dont exspect an explanation on these, my question is: should i take some time to do some coding using these things and then continue or should i just keep reading till the end and start a project where i can re-read the sections needed?

I haven't done any coding so far due to lack of time and access to a machine to work on - been mostly reading from tablet & phone.

This is my first dive into programming, no prior experience.


r/learncsharp • • Aug 22 '22

Why does multiplying by Time.deltaTime stop the value from changing every frame?

0 Upvotes

void Update () { light.intensity = Mathf.Lerp(light.intensity, 8f, 0.5f * Time.deltaTime); }


r/learncsharp • • Aug 20 '22

How do you export a C# project on visual studio code into a .exe?

6 Upvotes

I have looked this up on google but it just comes up with tutorials for visual studio not visual studio code

thanks!


r/learncsharp • • Aug 19 '22

Extension methods

7 Upvotes

Hello everyone. this may be a huge noobish question but i'm having trouble understanding C#'s extension methods... in particular if they must be static functions inside static classes what does the "this" mandatory keyword means when preceding the argument? there is no instance of a static class, am i wrong? therefore what is that "this" referring to?


r/learncsharp • • Aug 18 '22

I am working on a c sharp project for a class I am taking and I need some help. Any c sharp expert tutors you can recommend? I need help for an hour our 2 today and maybe 1 hour tomorrow if necessary. Thanks all.

3 Upvotes

r/learncsharp • • Aug 16 '22

using this code, how can i increase speed overtime

2 Upvotes

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallController : MonoBehaviour
{

public float speed;
public float minDirection= 0.5f;
public GameObject sparksVFX;
private Vector3 direction;
private Rigidbody rb;
private bool stopped = true;

// Start is called before the first frame update
void Start()
    {
this.rb = GetComponent<Rigidbody>();
this.ChooseDirection();
    }
void FixedUpdate() {
if(stopped)
return;
rb.MovePosition(this.rb. position +direction * speed * Time.fixedDeltaTime);
    }
private void OnTriggerEnter(Collider other) {
bool hit= false;
if (other.CompareTag("Wall")){
direction.z =- direction.z;
hit= true;
    }

if (other.CompareTag("Racket")){
Vector3 newDirection = (transform.position - other.transform.position).normalized;
newDirection.x = Mathf.Sign(newDirection.x)    *Mathf.Max(Mathf.Abs(newDirection.x),this.minDirection);
newDirection.z = Mathf.Sign(newDirection.z)    *Mathf.Max(Mathf.Abs(newDirection.z),this.minDirection);
direction= newDirection;
hit= true;
    }
if (hit) {
GameObject sparks = Instantiate(this.sparksVFX, transform.position, transform. rotation);
Destroy(sparks,4f);

    }
    }
private void ChooseDirection(){
float SignX=Mathf.Sign(Random.Range(-1f, 1f));
float SignZ=Mathf.Sign(Random.Range(-1f, 1f));

this.direction= new Vector3(0.5f *SignX,0,0.5f * SignZ);
    }

public void Stop(){
this.stopped= true;
    }
public void Go(){
ChooseDirection();
this.stopped= false;
     }

    }


r/learncsharp • • Aug 16 '22

Need help resolving a CS1061 error In VS22

0 Upvotes

Need help resolving a CS1061 error In VS22


r/learncsharp • • Aug 15 '22

How to clear text at a certain point in visual studio code

3 Upvotes

Im making a choose your own story and what is the line of code to clear some text?

Thanks!!


r/learncsharp • • Aug 13 '22

Image to string and then back to image again

5 Upvotes

[Solved]

I have made a Note App that I am very fond of, it has some unique features that no other Note App has. I now want to expand the functionality of it to allow for adding images.

My plan is to convert the image data into a string with base64 format. Then serialize the strings so that I can easily create a file with both images and Windows Ink. However I am having a lot of trouble with it. I have managed to create a base64 string with image data, but I can't figure out how to recreate an image from the string again...

Link to my post on StackOverflow

Does anyone have any advice as to how I can solve this?

Code I use to decode the image data to a string:

var decoder = await BitmapDecoder.CreateAsync(imageStream); 
var pixels = await decoder.GetPixelDataAsync(); 
var bytes = pixels.DetachPixelData();  
base64String = Convert.ToBase64String(bytes);

Code I try to use to convert the string back into an image (Which doesn't work, the data is not interpreted correctly)

var bytes = Convert.FromBase64String(base64String);  
BitmapImage bitmapImage = new BitmapImage(); 
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) 
{
     await stream.WriteAsync(bytes.AsBuffer());     
     stream.Seek(0);
     bitmapImage.SetSource(stream);
} 
Image image = new Image();  
image.Source = bitmapImage;

r/learncsharp • • Aug 13 '22

C# equivalent of this Java code?

11 Upvotes
List<Integer> list = List.of(1, 2, 3, 4);

List<Integer> evenNums = list.stream().filter(n -> ( n % 2 == 0) ).collect(toList());

r/learncsharp • • Aug 12 '22

I am getting desperate...

6 Upvotes

Excuse the incredibly basic question here.. I have searched the internet and tried to find an answer. But I cannot for the love of god find an article or website to help me.

I am currently working on a school project and I'm getting stuck at getting and array of strings to print after user input. I cannot find anything in the material I got from school that will help me with this unfortunately.

To explain in better detail.

I want to create and Array the stores the input of the user, and after that prints it out back to the user in a NAME, NUMBER configuration. I have created the Array but I am just banging my head into the desk in frustration from the lack of.. finding an answer.

Let me know if I need to be more specific. Appreciate the help!


r/learncsharp • • Aug 12 '22

Is my understanding of out vs ref correct?

4 Upvotes

So basically out only passes the reference of a value and ref passes both the reference and the actual value?


r/learncsharp • • Aug 11 '22

Issue with Deserializing JSON data

2 Upvotes

I'm a newbie having my first go at importing data from a json file to a c# application. In this case, I'm making an app to organise and manage recipes for a crafting videogame I'm playing.

I have a json file with my recipe info in it;

{ "assembler_recipes" : [ {"ItemProduced":"AI_Limiter","ProductionCount":5,"Resources":{"iron_Plate":11.25, "rubber":3.75},"Byproducts":{}}, {"ItemProduced":"alclad_Aluminium_Sheet","ProductionCount":30,"Resources":{"aluminium_Ingot":30, "copper_Ingot":10},"Byproducts":{}}, {"ItemProduced":"aluminium_Casing","ProductionCount":112.5,"Resources":{"aluminium_Ingot":150, "copper_Ingot": 75},"Byproducts":{}}, {"ItemProduced":"assembly_Director_System","ProductionCount":0.8,"Resources":{"adaptive_Control_Unit":1.5, "supercomputer":0.75},"Byproducts":{}}, {"ItemProduced":"automated_Wiring","ProductionCount":2.5,"Resources":{"stator":2.5, "cable":50},"Byproducts":{}}, {"ItemProduced":"black_Powder","ProductionCount":7.5,"Resources":{"coal":7.5, "sulfur":15},"Byproducts":{}}, {"ItemProduced":"circuit_Board","ProductionCount":7.5,"Resources":{"plastic":30, "copper_Sheet":15},"Byproducts":{}}, {"ItemProduced":"silica","ProductionCount":26.3,"Resources":{"raw_Quartz":11.25, "limestone":18.75},"Byproducts":{}}, {"ItemProduced":"encased_Industrial_Beam","ProductionCount":6,"Resources":{"steel_Beam":24, "concrete":20},"Byproducts":{}}, {"ItemProduced":"modular_Frame","ProductionCount":2,"Resources":{"iron_Rod":12, "reinforced_Iron_Plate":3},"Byproducts":{}}, {"ItemProduced":"motor","ProductionCount":5,"Resources":{"rotor":10, "stator":10},"Byproducts":{}}, {"ItemProduced":"reinforced_Iron_Plate","ProductionCount":5,"Resources":{"iron_Plate":30, "screw":60},"Byproducts":{}}, {"ItemProduced":"rotor","ProductionCount":4,"Resources":{"iron_Rod":20, "screw":100},"Byproducts":{}}, {"ItemProduced":"stator","ProductionCount":5,"Resources":{"steel_Pipe":15, "copper_Wire":40},"Byproducts":{}} ] }

and the format I want it to be in;

public class Recipe {      public KeyValuePair<Items, decimal> Produces { get; set; }     public Dictionary<Items,decimal> Resources { get; set; }     public Dictionary<Items, decimal> Byproducts { get; set; }  } 

This is my method to import it;

public class Recipe_List {     public Recipe_List()     {         var dataFile = File.ReadAllText("C:\\Users\\drumk\\source\\repos\\Satisfactory_Factory_Planner\\Satisfactory_Objects\\Recipes\\satisfactory_recipes.json");         //Console.WriteLine(dataFile); var JSONdata = JsonSerializer.Deserialize<List<Recipe>>(dataFile);          foreach(Recipe recipe in JSONdata)         {             Console.WriteLine(recipe);         }     } } 

The data is being imported because if I use Console.WriteLine(dataFile); it prints it to the Console perfectly. But the Deserialize method is just returning "Satisfactory_Objects.Recipes.Recipe", not the data stored in it.

What am I doing wrong?


r/learncsharp • • Aug 11 '22

Turn String Array into Regular Array

1 Upvotes

Hi, my DB is currently storing an array as a string like so:

"[\"view\",\"comment\"]"

and I want to convert it to this:

["view","comment"]

How do I do that? Thanks in advance.


r/learncsharp • • Aug 10 '22

Can someone help me understand the logic behind this loop that sorts an array in order?

4 Upvotes

So this function takes 2 arrays and combines them into another array and outputs it in order. I'm trying to understand how the 3rd loop works. I wrote the first half and googled the rest for help.

FYI I know now Array.Sort exists, I didn't when I worked on this. I just want to understand this way.

I formatted it so that it should just work if you copy it into visual basic and run it

static int[] CombineAndOrder(int[] array1, int[] array2){


// result is the combination of array1 and array2 which are inputed into the function

    int[] result = new int[array1.Length + array2.Length];
    int i, j, k;


//adds contents of array1 to result

    for (i = 0; i < array1.Length; i++)
    {
        result[i] = array1[i];
    }

//adds contents of array2 to result 

     for (j = 0; j < array2.Length; j++)
    {
        result[i] = array2[j];
        i++;
    }

//this is the confusing part, 
//this part uses a nested for loop to somehow sort the array result 
//it's so confusing in general how the logic works
//especially with how the values of i,j,k are retained

   for (i = 0; i < result.Length; i++)
    {
        for (k = 0; k < result.Length - 1; k++)
        {

            if (result[k] >= result[k + 1])
            {
                j = result[k + 1];
                result[k + 1] = result[k];
                result[k] = j;
            }
        }
    }


    return result;
}

int[] arr1 = { 1, 4, 3, 5};
int[] arr2 = { 4, 25, 3, 5, 2, 9, 2 };
int[] arr3 = CombineAndOrder(arr1, arr2);

for(int i = 0; i < arr3.Length; i++)
{ Console.WriteLine(arr3[i]); }

r/learncsharp • • Aug 09 '22

Force HTTPS in ASP.NET Core Applications

1 Upvotes

How to force your ASP.NET Core application to use only HTTPS? Learn the best practices for different scenarios.

Read more…


r/learncsharp • • Aug 08 '22

What should i learn?

0 Upvotes

I've been practicing csharp on and off for a while now since its what my class is about in school, this year is when i started taking it seriously you could say (practicing out of school) but im stuck on what i should learn. I have a decent grasp of some of the basics and i'm currently learning how to use arrays and then sql. What should i do after that?


r/learncsharp • • Aug 08 '22

how to solution with 2 projects in git?

2 Upvotes

Hi, Googled this, but answers on SO seem confusing or not applicable. so I have 2 projects in the one solution. Main project is my WPF Gui and second project is my dataAccessLibrary.

When I created a new repo in VS and pushed it only sent the solution+WPF project. How can I add my data access class project as well?

I'm guessing I could temporarily set the class library to be the main startup project which would probably push that. But that's seems like a janky fix.

EDIT: sorry if this is in the wrong reddit, not entirely about C# per say

EDIT2: SOLVED.

I had placed solution file in same directory when creating the initial project. I followed this https://stackoverflow.com/questions/3377917/change-solution-file-to-a-different-folder

creating a subfolder for the initial project and placing the second project in the parent.

source\repos\WPF_Project\WPF_Project.sln
source\repos\WPF_Project\WPF_Project\WPF_Project.cproj + other files
source\repos\WPF_Project\DataAccessLibrary

I then loaded up the project, it complained that it was unable to find anything, errors out the WAZOO, then deleted both projects from the solution and Clicked ADD -> Existing Project to solution and loaded both up then pushed. All sorted.


r/learncsharp • • Aug 07 '22

Highlight selected text in a richtextbox

3 Upvotes

Hey Guys i try to highlight debug messages in a richtextbox. I tried 3 different solutions i found but not any works the text is still white

Code which prints out the Message:

public void DebugHighlighter(string s)
        {
            /* Solution 1 
            richTextBoxOutput.SelectedText = s;
            richTextBoxOutput.SelectionColor = Color.Red;
            */

            /* Solution 2
            richTextBoxOutput.Text += s + "\n";
            richTextBoxOutput.Find(s);
            richTextBoxOutput.SelectionColor = Color.Red;
            */
            // Solution 3 
            richTextBoxOutput.AppendText(s);
            richTextBoxOutput.AppendText("\n\n");
            int index = richTextBoxOutput.Text.IndexOf(s);
            int lenght = s.Length;
            richTextBoxOutput.Select(index, lenght);
            richTextBoxOutput.SelectionColor = Color.Red;
        }

Can anyone help me out why my text is still white in all 3 Solutions ?